如何自动打开微信并发送消息
首先导入库:
from pywinauto import application
再确定控件的分析模式:
app = application.Application(backend='win32')
或:
app = application.Application(backend='uia')
本人的方法就是尝试,看哪种分析模式不会报错,如若错误会报错:
UserWarning: 32-bit application should be automated using 32-bit Python (you use 64-bit Python)
warnings.warn(
再连接窗口,有两种方法
第一种是连接已打开的窗口,用管理员身份打开inspector,获得窗口的信息,进行连接:
app.connect(title_re='微信', class_name='WeChatMainWndForPC') # 窗口名和类名
第二种是根据应用程序(exe文件)的路径打开应用程序:
app.start('D:\微信\WeChat\WeChat.exe')
再打印对应窗口的控件信息:
app.window(title_re='微信', class_name='WeChatMainWndForPC').print_control_identifiers()
在打印出来的信息最后找到输入框:
Edit - '输入' (L1155, T762, R1912, B847) ['Edit5', '21:38Edit'] child_window(title="输入", control_type="Edit")
发送按钮:
Button - 'sendBtn' (L1749, T852, R1874, B892) ['sendBtnButton', 'Button60', 'sendBtn'] child_window(title="sendBtn", control_type="Button")
在输入框输入“你好”:
app.window(title_re='微信', class_name='WeChatMainWndForPC').child_window(title="sendBtn", control_type="Button").type_keys('你好')
再点击发送按钮:
app.window(title_re='微信', class_name='WeChatMainWndForPC').sendBtn.click()
这里注意.click()有时不起作用,采用更加真实的点击.click_input():
app.window(title_re='微信', class_name='WeChatMainWndForPC').sendBtn.click_input()
但是这样比较耗时,故可以导入pywinauto.keyboard来模拟输入回车:
from pywinauto.keyboard import send_keys
send_keys('{ENTER}')
注意输入回车不要写成:
app.window(title_re='微信', class_name='WeChatMainWndForPC').child_window(title="sendBtn", control_type="Button").send_keys('{ENTER}')