目录
1. 连接窗口
核心:连接分两步——先选 backend,再定位窗口。定位窗口优先用标题 / 类名 / 进程,handle 是「遍历 Desktop 之后才拿到」的东西,不是预先写在代码里的常量。
1.1 选 backend
默认 backend 是
'win32',操作微信、浏览器这类必须显式写backend='uia'。
1.2 按标题 / 类名连接(最常用)
知道窗口标题或类名,直接连:
from pywinauto import Application, Desktop
# 方式 A:Application —— 连接已运行的应用,再取主窗口
app = Application(backend='uia').connect(title='微信')
wechat_window = app.window(title='微信')
# 方式 B:Desktop —— 跳过连接应用,直接取桌面上的窗口(更省事)
wechat_window = Desktop(backend='uia').window(title='微信')
# 标题不完全确定时用正则
wechat_window = Desktop(backend='uia').window(title_re='.*微信.*')
# 类名:微信 4.x 主窗口
wechat_window = Desktop(backend='uia').window(class_name='mmui::MainWindow')
标题和类名可以同时传给
window()缩小范围:window(title='微信', class_name='mmui::MainWindow')。
1.3 按进程 / exe 路径连接(注意多进程坑)
from pywinauto import Application
app = Application(backend='uia').connect(process=22736) # PID
app = Application(backend='uia').connect(path=r'D:\Weixin\Weixin.exe') # exe 路径
wechat_window = app.window(class_name='mmui::MainWindow')
多进程坑:微信 4.x 有多个
Weixin.exe进程,connect(path=...)可能连到不含主窗口的那个进程,导致window(class_name=...)报ElementNotFoundError: {..., 'process': xxxx}。报错里带process字段基本就是这个问题。解决:别用 path 连,改用
Desktop(backend='uia').window(class_name='mmui::MainWindow')在整个桌面范围按类名找,绕开进程过滤。
1.4 连不上时:遍历 Desktop 找窗口(handle 从这里来)
不知道窗口确切信息、或上面都连不上时,先打印桌面上所有活跃窗口,看真实标题 / 类名 / 进程 / 句柄:
from pywinauto import Desktop
for w in Desktop(backend='uia').windows():
print(w.handle, w.class_name(), repr(w.window_text()), w.element_info.process_id)
输出示例,找到目标那一行:
1349678 mmui::MainWindow 'Weixin' 22316
然后用打印出来的信息连接。想用 handle 连,就把这个数字传进去(必须关键字传参):
from pywinauto import Desktop, Application
desktop = Desktop(backend='uia')
wechat_window = desktop.window(handle=1349678) # 正确
# wechat_window = desktop.window(1349678) # 报错:定位参数必须 kwargs
# Application 同理
app = Application(backend='uia').connect(handle=1349678)
wechat_window = app.window(handle=1349678)
handle 的正确来源:① 上面的
Desktop.windows()遍历;②win32gui.FindWindow(class_name, title)动态查找。handle 会随进程重启变化,不要当常量写死。另外
Desktop只能连已打开且活跃的窗口(前台或最小化到任务栏),连不了已关闭的。
2. 定位控件
拿到 WindowSpecification 后,在窗口内找控件。定位参数用 title / control_type / auto_id / class_name 这些,不知道值时直接 wechat_window.dump_tree() 打印控件树,可定位的控件会给出 child_window 语句,复制即用。
2.1 找单个控件:child_window
child_window 返回单个 WindowSpecification,定位参数按实际代码写——搜索栏只用 class_name,聊天输入框用 auto_id:
from pywinauto import Desktop
wechat_window = Desktop(backend='uia').window(class_name='mmui::MainWindow')
# 顶部搜索栏:实际代码里只按 class_name 定位,没有 title / control_type
search_edit = wechat_window.child_window(class_name='mmui::XValidatorTextEdit')
# 聊天输入框:按 auto_id 定位
chat_edit = wechat_window.child_window(auto_id='chat_input_field')
层级再深也能一次定位;定位参数全是 kwargs,建议写成字典用 ** 解包,方便复用:
search_list = {'auto_id': 'search_list', 'control_type': 'List'}
mention_list = {'auto_id': 'chat_mention_list', 'control_type': 'List'}
# 链式
wechat_window.child_window(**search_list).child_window(**mention_list)
# 或直接找
wechat_window.child_window(**mention_list).children()[0].click_input()
window()是child_window()的弃用别名,两者没区别,统一用child_window()。
2.2 找一类控件:descendants / children
返回列表,需要判空或用 [0]。区别:descendants 递归深度查找,children 只取直接子控件。
# children:只取子控件 —— 遍历搜索结果列表的每一项
search_result_list = wechat_window.child_window(auto_id='search_list', control_type='List')
for item in search_result_list.children():
print(item.window_text())
# descendants:深度查找 —— 遍历聊天区所有文本控件
texts = wechat_window.descendants(class_name='mmui::XTextView')
if texts:
for t in texts:
print(t.window_text())
descendants/children返回的是xxxWrapper对象列表,不是WindowSpecification,不能用exists(),只能判空。child_window/window返回的才是WindowSpecification。
2.3 打印控件树:dump_tree
不知道控件参数时,直接在代码里打印:
wechat_window.dump_tree()
# 等价于 wechat_window.print_control_identifiers()
dump_tree本质是print_control_identifiers的别名,输出一致,会列出每个控件的定位信息,直接抄下来用。
3. 判断控件是否存在 / 等待出现
3.1 exists(推荐)
返回 bool,超时不抛异常,适合直接写进业务代码:
mention_list = wechat_window.child_window(auto_id='chat_mention_list', control_type='List')
if not mention_list.exists(timeout=1):
print('@ 候选框没弹出:@ 的人可能不对')
else:
mention_list.children()[0].click_input()
exists只对child_window/window返回的WindowSpecification有效,descendants/children的返回值不能用。
3.2 wait / wait_not
等待出现 / 消失,超时抛 TimeoutError,需捕获:
from pywinauto.timings import TimeoutError
try:
mention_list = wechat_window.child_window(auto_id='chat_mention_list', control_type='List')
mention_list.wait(timeout=2, wait_for='exists')
except TimeoutError:
print('候选框没出现')
wait_for可选:exists(有效句柄)、visible(未隐藏)、enabled(未禁用)、ready(可见且启用)、active(活动状态)。wait_not用wait_for_not,取值相同。单纯判断存在用exists更省事。
4. 读取控件信息
4.1 常用属性
print(wechat_window.window_text()) # 标题 / 文本
print(wechat_window.class_name()) # 类名
print(wechat_window.automation_id()) # AutomationId
print(wechat_window.control_id()) # 控件 ID
print(wechat_window.process_id()) # 进程 ID
print(wechat_window.rectangle()) # 位置和尺寸 (left, top, right, bottom)
print(wechat_window.parent()) # 父控件
print(wechat_window.children()) # 子控件列表
底层信息在 element_info 里,上面的方法多数是它的 getter:
e = wechat_window.element_info
print(e.name, e.class_name, e.control_type, e.automation_id, e.handle, e.process_id)
实际代码里读会话标题——auto_id 很长,直接从 dump_tree 抄:
now_title = wechat_window.child_window(
auto_id='content_view.top_content_view.title_h_view.left_v_view.left_content_v_view.left_ui_.big_title_line_h_view.current_chat_name_label'
)
print(now_title.window_text()) # 例如:K123下单测试
4.2 状态与文本
search_result_list = wechat_window.child_window(auto_id='search_list', control_type='List')
print(search_result_list.is_enabled()) # 是否启用
print(search_result_list.is_visible()) # 是否可见
print(search_result_list.has_keyboard_focus()) # 是否有键盘焦点
# 取文本:wrapper 用 window_text(),没有 name 属性
texts = [t.window_text() for t in wechat_window.descendants(class_name='mmui::XTextView')]
5. 点击与输入
5.1 点击
chat_edit = wechat_window.child_window(auto_id='chat_input_field')
chat_edit.click_input() # 单击
chat_edit.double_click_input() # 双击
chat_edit.right_click_input() # 右键
chat_edit.press_mouse_input() # 按下鼠标
chat_edit.release_mouse_input() # 释放鼠标
动作方法(
click_input/type_keys)返回None,不能链式。必须分步:chat_edit.click_input()一行,chat_edit.type_keys('x')一行。
5.2 输入
from pywinauto.keyboard import send_keys
chat_edit.type_keys('测试', with_spaces=True) # 模拟打字
chat_edit.type_keys('{ENTER}') # 按键,如回车
chat_edit.set_text('测试') # 直接设置文本,会清空原内容
send_keys('{BACKSPACE}') # 全局快捷键:删光标前一个字符(往回删)
send_keys('{DELETE}') # 删光标后一个字符;光标在末尾时按它无效
send_keys('^v') # Ctrl+V
DELETE 与 BACKSPACE:输入完光标在末尾,
{DELETE}删的是光标右边(空的),什么也删不掉;往回删要用{BACKSPACE}。连删写{BACKSPACE 3}。
type_keys打中文到微信 Qt 输入框经常无效,中文改走剪贴板:pyperclip.copy(text)再send_keys('^v')。
5.3 发送图片(剪贴板 CF_DIB)
微信认剪贴板里的位图格式,粘贴后是图片消息。函数定义一次,发图时调用:
import win32clipboard
from PIL import Image
from io import BytesIO
from pywinauto.keyboard import send_keys
def copy_image(path):
img = Image.open(path).convert('RGB')
buf = BytesIO()
img.save(buf, 'BMP')
data = buf.getvalue()
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardData(win32clipboard.CF_DIB, data[14:]) # 去掉 BMP 文件头 14 字节
win32clipboard.CloseClipboard()
# 用:聚焦输入框 → 贴图 → 发送
wechat_window.child_window(auto_id='chat_input_field').click_input()
copy_image(r'G:\RPA合集\开发中\仓库\data\发货清单截图\202.png')
send_keys('^v')
send_keys('{ENTER}')
data[14:]不能省:CF_DIB要的是从BITMAPINFOHEADER起的纯位图数据,BMP 那 14 字节文件头必须去掉,否则粘贴是空白。pyperclip只支持文本,图片必须用win32clipboard。
剪贴板是全局资源,
OpenClipboard后必须配对CloseClipboard,否则锁死。稳妥写法用try/finally包住中间两步。
成功判定看已发送的图片气泡,不要用「输入框清空」当成功标志(粘贴失败输入框也会空)。
6. 坐标级鼠标 / 键盘操作
当控件定位不到、只能点屏幕某个位置时用。所有鼠标操作都要 coords=(x, y) 屏幕坐标。
from pywinauto import mouse, keyboard
# 鼠标
mouse.click(button='left', coords=(200, 200)) # 单击,button='right' 为右键
mouse.double_click(coords=(200, 200)) # 双击
mouse.move(coords=(300, 300)) # 移动
mouse.scroll(wheel_dist=-20, coords=(1000, 500)) # 滚动,负=向下,正=向上
# 键盘
keyboard.send_keys('^a') # Ctrl+A
keyboard.send_keys('^v') # Ctrl+V
keyboard.send_keys('{ENTER}')
mouse 模块共 8 种操作:
click、double_click、right_click、move、press、release、scroll、wheel_click。追求复杂热键可用pyautogui。
7. 实战:微信 4.1+ 自动化完整流程
把上面各步串起来:连接 → 激活 → 搜索会话 → 打开 → @人 → 输入 → 发图。
from pywinauto import Desktop
from pywinauto.keyboard import send_keys
# 1. 连接 + 激活(微信 4.x 主窗口类名 mmui::MainWindow)
wechat_window = Desktop(backend='uia').window(class_name='mmui::MainWindow')
wechat_window.restore() # 从最小化恢复
wechat_window.set_focus() # 激活到前台
# 2. 搜索会话:搜索栏只按 class_name 定位,输入搜索词
search_edit = wechat_window.child_window(class_name='mmui::XValidatorTextEdit')
search_edit.click_input()
search_edit.type_keys('k123')
# 3. 遍历搜索结果,按分组名归类(联系人 / 群聊 / 最常使用 ...)
search_result_list = wechat_window.child_window(auto_id='search_list', control_type='List')
result = {'联系人': [], '群聊': [], '聊天记录': [], '聊天文件': [], '最常使用': [], '更多': [], '网络查找微信号:': []}
current = None
for item in search_result_list.children():
if item.window_text() in result:
current = item.window_text()
else:
result[current].append({'name': item.window_text(), 'element': item})
# 4. 打开目标会话(群聊或最常使用里唯一的那个)
if len(result['最常使用']) == 1:
item = result['最常使用'][0]['element']
elif len(result['群聊']) == 1:
item = result['群聊'][0]['element']
else:
raise RuntimeError('会话列表和搜索里都没找到群')
item.click_input()
# 5. 校验打开的是不是目标会话(标题 auto_id 很长,从 dump_tree 抄)
now_title = wechat_window.child_window(
auto_id='content_view.top_content_view.title_h_view.left_v_view.left_content_v_view.left_ui_.big_title_line_h_view.current_chat_name_label'
)
if 'k123' in now_title.window_text().lower(): # lower() 避免 k123 / K123 大小写不匹配
print('已正确打开会话', now_title.window_text())
else:
raise RuntimeError('未正确打开会话', now_title.window_text())
# 6. @人:先输末段名,候选不唯一/没弹出就输完整名
for mention in ['鑫逸老爸', '鑫逸 老妈']:
split_mention = mention.split(' ')[-1]
wechat_window.child_window(auto_id='chat_input_field').type_keys('@' + split_mention)
mention_list = wechat_window.child_window(auto_id='chat_mention_list', control_type='List')
if not mention_list.exists() or len(mention_list.children()) > 1:
for _ in range(len(split_mention)):
send_keys('{BACKSPACE}')
wechat_window.child_window(auto_id='chat_input_field').type_keys(mention)
print('候选不唯一,已输入完整名,请检查')
else:
mention_list.children()[0].click_input()
# 7. 输入正文
wechat_window.child_window(auto_id='chat_input_field').type_keys('测试')
# 8. 贴图片发送(copy_image 定义见 5.3)
wechat_window.child_window(auto_id='chat_input_field').click_input()
copy_image(r'G:\RPA合集\开发中\仓库\data\发货清单截图\202.png')
send_keys('^v')
8. 注意事项
control_type 只认短名,不认 UIA 常量全名:inspect.exe 是微软官方 UIA 查看工具,显示的是 UIA 底层常量原名
UIA_TextControlTypeId——UIA_= UI Automation 前缀,Text= 控件类型,ControlTypeId= 后缀。pywinauto 封装了 UIA,内部known_control_types映射表把短名翻译成常量:'Text'→UIA_TextControlTypeId、'Edit'→UIA_EditControlTypeId、'List'→UIA_ListControlTypeId、'ListItem'→UIA_ListItemControlTypeId、'Button'→UIA_ButtonControlTypeId。