截图与 OCR
窗口截图和文字识别工具函数。
截图
capture_window(hwnd, mode="auto")
对指定窗口截图。
- hwnd
int— 窗口句柄 - mode
str— 截图模式:"auto"/"bitblt"/"print_window"/"window_capture" - 返回
bytes— PNG 格式图片数据
capture_control(control, hwnd=None)
对指定 UIAutomation 控件截图。
- control
Control— 目标控件 - hwnd
int | None— 窗口句柄(自动获取) - 返回
bytes— PNG 格式图片数据
capture_by_bitblt(hwnd, rect=None)
使用 BitBlt 方式截图(需窗口可见)。
- hwnd
int— 窗口句柄 - rect
Tuple | None— 截取区域 - 返回
bytes
capture_by_print_window(hwnd, rect=None)
使用 PrintWindow 方式截图(支持后台窗口)。
- hwnd
int— 窗口句柄 - rect
Tuple | None— 截取区域 - 返回
bytes
capture_by_window_capture(hwnd, rect=None)
使用 Windows Graphics Capture API 截图。
- hwnd
int— 窗口句柄 - rect
Tuple | None— 截取区域 - 返回
bytes
截图模式对比
| 模式 | 后台支持 | 性能 | 兼容性 |
|---|---|---|---|
bitblt | ❌ 需可见 | 快 | 最佳 |
print_window | ✅ | 中等 | 大部分窗口 |
window_capture | ✅ | 快 | Win10+ |
Weixin 实例的截图方法
python
wx = Weixin()
# 微信主窗口截图
png_data = wx.get_screenshot()
# 保存到文件
wx.screenshot("C:/screenshot.png")OCR 文字识别
通过 Weixin 实例使用 OCR:
wx.ocr(image)
识别图片中的文字。
- image
bytes | str— PNG 图片数据或文件路径 - 返回
dict—{text: {center, left_top, right_bottom, width, height}}
wx.get_image_text(image)
同 wx.ocr(image)。
OCR 引擎
| 引擎 | 说明 |
|---|---|
wcocr | 微信自带 OCR 组件,速度快、准确率高(默认) |
rapidocr | 开源 OCR 引擎,无需微信 OCR 插件 |
python
# 使用微信OCR(默认)
wx = Weixin(ocr="wcocr")
# 使用 RapidOCR
wx = Weixin(ocr="rapidocr")示例
python
from pywxauto import Weixin
from pywxauto.wx import capture_window, capture_control
wx = Weixin()
# 截图并OCR
png = wx.get_screenshot()
result = wx.ocr(png)
for text, info in result.items():
print(f"文字: {text}, 位置: {info['center']}")