# py-auto **Repository Path**: kajum/py-auto ## Basic Information - **Project Name**: py-auto - **Description**: python自动化 - **Primary Language**: Python - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 1 - **Created**: 2024-11-08 - **Last Updated**: 2026-09-15 ## Categories & Tags **Categories**: Uncategorized **Tags**: Python ## README # UIAUTOMATION ## 前言 > ‌**[UIAutomation](https://www.baidu.com/s?rsv_dl=re_dqa_generate&sa=re_dqa_generate&wd=UIAutomation&rsv_pq=e70e364f00babb5c&oq=uiautomation&rsv_t=a123hnFXoOY3PxCDkDgBhWHcO1sOUyNNvctaedAlDAPedIn3vMXtiX8ncEw&tn=baidu&ie=utf-8)**‌是微软开发的一个辅助功能框架,主要用于自动化测试和辅助技术。它通过提供对用户界面(UI)信息的编程访问,满足自动化测试和辅助技术产品的需求。UIAutomation适用于[Windows](https://www.baidu.com/s?rsv_dl=re_dqa_generate&sa=re_dqa_generate&wd=Windows&rsv_pq=e70e364f00babb5c&oq=uiautomation&rsv_t=a123hnFXoOY3PxCDkDgBhWHcO1sOUyNNvctaedAlDAPedIn3vMXtiX8ncEw&tn=baidu&ie=utf-8)操作系统,通过五个组件实现编程访问:UI自动化树、UI自动化元素、UI自动化属性、控件模式和UI自动化事件‌ > > 而后续提及的UIAutomation是 [yinkaisheng](https://github.com/yinkaisheng) 使用python开发的模块, 本质上是对微软的 UIAutomation API 进行了封装 > > ## 使用场景 + **自动化测试**‌:通过编程方式模拟用户操作,进行自动化测试,提高测试效率和准确性 + **辅助技术**‌:帮助残障人士更好地使用计算机和应用程序,提供无障碍访问功能 ## UI查看工具介绍 + **automation.py** , 这个是安装 uiautomation 这个模块后自带的命令行工具, [详细使用方法 ](https://github.com/yinkaisheng/Python-UIAutomation-for-Windows/blob/master/readme_cn.md) + **inspect.exe** , 是windows工具包的其中一个工具 , 这个比较好用,后续都会用到这个工具去查看UI节点 , [下载地址](https://docs.microsoft.com/zh-cn/windows/win32/winauto/inspect-objects) ## 环境准备 + Python 3.7.9 + inspect.exe + uiautomation 模块 + wxauto 模块 + plyer 模块 + emoji 模块 ## 安装必要的python模块 ```shell pip3 install uiautomation pip3 install wxauto pip3 install plyer pip3 install emoji ``` ## uiautomation - Sendkey及Sendkeys进行热键的输入 ### SendKey + 函数入参 ```python def SendKey(key: int, waitTime: float = OPERATION_WAIT_TIME) -> None # 参数解析 key: 类“Keys”中的值 waitTime: 等待时间 ``` + SendKey中的key ```python class Keys: VK_LBUTTON = 0x01 鼠标左键 VK_RBUTTON = 0x02 鼠标右键 VK_CANCEL = 0x03 控制中断处理 VK_MBUTTON = 0x04 鼠标中键(三键鼠标) VK_XBUTTON1 = 0x05 X1 鼠标按键 VK_XBUTTON2 = 0x06 X2 鼠标按键 VK_BACK = 0x08 退格键 VK_TAB = 0x09 TAB 键 VK_CLEAR = 0x0C 清除键 VK_RETURN = 0x0D 回车键 VK_ENTER = 0x0D VK_SHIFT = 0x10 SHIFT 键 VK_CONTROL = 0x11 CTRL 键 VK_MENU = 0x12 ALT 键 VK_PAUSE = 0x13 暂停键 VK_CAPITAL = 0x14 大写锁定键 VK_ESCAPE = 0x1B ESC键 VK_SPACE = 0x20 空格键 VK_LEFT = 0x25 左箭头键 VK_UP = 0x26 向上箭头键 VK_RIGHT = 0x27 右箭头键 VK_DOWN = 0x28 向下箭头键 VK_DELETE = 0x2E DEL 键 VK_0 = 0x30 0 键 VK_1 = 0x31 1 键 VK_A = 0x41 A 键 VK_B = 0x42 B 键 VK_F1 = 0x70 F1 键 VK_F2 = 0x71 F2 键 ``` + 一般使用 ```python import uiautomation as auto auto.SendKey(auto.Keys.VK_DOWN) ``` ### Sendkeys + 函数入参 ```python def SendKeys(text: str, interval: float = 0.01, waitTime: float = OPERATION_WAIT_TIME, charMode: bool = True, debug: bool = False) -> None # 参数解析 text: 用于键入的键,也可以直接传任意字符串 interval: 间隔, 键间隔之间的秒数 waitTime: 等待时间 charMode: 如果为Flase, 则键入文本取决于输入法 debug: 如果为True,则打印密钥 ``` + text键入的值 | 值 | 按键描述 | | :------------------------------------------------: | :----------------------------------------------------------: | | SendKeys('{Enter}') | 回车 | | SendKeys('{Ctrl}') | ctrl | | SendKeys('{Delete}') | delete | | SendKeys('{Alt}') | alt | | SendKeys('{Space}') | 空格 | | SendKeys('{Shift}') | shift | | SendKeys('{Ctrl}a') | ctrl + a | | SendKeys('{Ctrl}v') | ctrl + v | | SendKeys('{Ctrl}{Shift}s') | ctrl + shift + v | | SendKeys('{a 3}{B 5}') | 输入a 3次 , b 5次 | | {}Hello{}}abc {a}{b}{c} test{} 3}{!}{a} (){(}{)}') | 结果:{Hello}abc abc test}}}!a ()() ,即{}中无内容,则去掉{},有内容则进行判断 | | SendKeys('0123456789{Enter}') | 表示输入0123456789,然后回车 | | SendKeys('{Ctrl}c') | ctrl + c | + 一般使用 ```python import uiautomation as auto # 输入 "hello" , 然后按下回车 auto.SendKeys('hello{Enter}') ``` ## uiautomation API - 上 ### 单击鼠标左键 + 函数定义 ```python def Click(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) # 参数解析 x: 横坐标 y: 纵坐标 waitTime: 等待时间,默认0.5 ``` + 示例 ```python import uiautomation as auto # 在坐标500,500的位置单击左键一次,并等待2秒 auto.Click(500,500) ``` ### 单机鼠标中键 + 函数定义 ```python def MiddleClick(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) # 参数解析 x: 横坐标 y: 纵坐标 waitTime: 等待时间,默认0.5 ``` + 示例 ```python import uiautomation as auto # 在坐标500,500的位置单击中键一次,并等待2秒 auto.MiddleClick(500,500) ``` ### 单机鼠标右键 + 函数定义 ```python def RightClick(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) # 参数解析 x: 横坐标 y: 纵坐标 waitTime: 等待时间,默认0.5 ``` + 示例 ```python import uiautomation as auto # 在坐标500,500的位置单击右键一次 auto.RightClick(500,500) ``` ### 按住鼠标左键 + 函数定义 ```python def PressMouse(x: int, y: int, waitTime: float = OPERATION_WAIT_TIME) # 参数解析 x: 横坐标 y: 纵坐标 waitTime: 等待时间,默认0.5 ``` + 示例 ```python import uiautomation as auto # 在坐标500,500的位置按住左键 auto.PressMouse(500,500) ``` ### 松开鼠标左键 + 函数定义 ```python def ReleaseMouse(waitTime: float = OPERATION_WAIT_TIME) # 参数解析 waitTime: 等待时间,默认0.5 ``` + 示例 ```python import uiautomation as auto # 在坐标500,500的位置按住左键,然后松开 auto.PressMouse(500,500) auto.ReleaseMouse() ``` ### 鼠标移动 + 函数定义 ```python def MoveTo(x: int, y: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) # 参数解析 x: 横坐标 y: 纵坐标 moveSpeed: 1 正常速度,< 1 移动速度较慢,> 1 移动速度更快。 waitTime: 等待时间,默认0.5 ``` + 示例 ```python import uiautomation as auto # 移动到坐标 200,300 处 auto.MoveTo(200,300) ``` ### 鼠标左键拖放 + 函数定义 ```python def DragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) # 参数解析 x1: 起始横坐标 y1: 起始纵坐标 x2: 目标横坐标 y2: 目标纵坐标 moveSpeed: 1 正常速度,< 1 移动速度较慢,> 1 移动速度更快。 waitTime: 等待时间,默认0.5 ``` + 示例 ```python import uiautomation as auto # 用左键从 300,300 拖放到 1000,300 auto.DragDrop(300,300,1000,300) ``` ### 鼠标右键拖放 + 函数定义 ```python def RightDragDrop(x1: int, y1: int, x2: int, y2: int, moveSpeed: float = 1, waitTime: float = OPERATION_WAIT_TIME) # 参数解析 x1: 起始横坐标 y1: 起始纵坐标 x2: 目标横坐标 y2: 目标纵坐标 moveSpeed: 1 正常速度,< 1 移动速度较慢,> 1 移动速度更快。 waitTime: 等待时间,默认0.5 ``` + 示例 ```python import uiautomation as auto # 用右键从 300,300 拖放到 1000,300 auto.DragDrop(300,300,1000,300) ``` ### 鼠标滚轮向下 + 函数定义 ```python def WheelDown(wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME) # 参数解析 wheelTimes:轮次,默认为1 interval: 间隔,默认为0.05 waitTime: 等待时间,默认为0.5 ``` + 示例 ```python import time import uiautomation as auto # 5秒后,向下滚动3次 time.sleep(5) auto.WheelDown(3) ``` ### 鼠标滚轮向上 + 函数定义 ```python def WheelUp(wheelTimes: int = 1, interval: float = 0.05, waitTime: float = OPERATION_WAIT_TIME) # 参数解析 wheelTimes:轮次,默认为1 interval: 间隔,默认为0.05 waitTime: 等待时间,默认为0.5 ``` + 示例 ```python import uiautomation as auto # 5秒后,向上滚动3次 time.sleep(5) auto.WheelUp(3) ``` ### 获取屏幕尺寸 + 函数定义 ``` def GetScreenSize() ``` + 示例 ```python import uiautomation as auto print( auto.GetScreenSize() ) ``` ### 确定窗口是否最小化 + 函数定义 ````python def IsIconic(handle: int) -> bool # 参数解析 handle:本机窗口的句柄 ```` ### 确定窗口是否最大化 + 函数定义 ```python def IsZoomed(handle: int) -> bool # 参数解析 handle:本机窗口的句柄 ``` ### 桌面是否被锁 + 函数定义 ```python IsDesktopLocked() -> bool # ps: # 如果按 Win+L、Ctrl+Alt+Del 或在远程桌面模式下,桌面将被锁定 ``` ### 按下键盘 + 函数定义 ```python def PressKey(key: int, waitTime: float = OPERATION_WAIT_TIME) -> None # 参数解析 key: Keys类中的枚举 waitTime: 等待时间 ``` ### 是否键盘 + 函数定义 ```python def ReleaseKey(key: int, waitTime: float = OPERATION_WAIT_TIME) -> None # 参数解析 key: Keys类中的枚举 waitTime: 等待时间 ``` ### 判断键盘是否被按下 + 函数定义 ````python def IsKeyPressed(key: int) -> bool # 参数解析 key: Keys类中的枚举 ```` ## uiautomation API - 中 ### 获取剪贴板文本 + 函数定义 ```python def GetClipboardText() -> str ``` ### 设置剪贴板文本 + 函数定义 ```python def SetClipboardText(text: str) -> bool # 参数解析 text: 需要设置的文本 ``` ### 获取剪贴板HTML + 函数定义 ```python def GetClipboardHtml() -> str # ps: # 位置(StartHTML, EndHTML ...)对utf-8编码的html文本有效,当utf-8编码的html文本解码为Python unicode str时,位置可能与返回的str中的实际位置不对应. ``` ### 设置剪贴板HTML + 函数定义 ```python def SetClipboardHtml(htmlText: str) -> bool # 参数解析 htmlText: 需设置的HTML文本 ``` ### 键盘快捷键 + 函数定义 ```python def KeyboardShortcut(self) -> str # 返回值: # 返回 str,元素的 Microsoft Active Accessibility 键盘快捷方式属性 ``` ### Name + 函数定义 ```python def Name(self) -> str # 返回值 # 返回 str,元素的 Microsoft Active Accessibility 名称属性 ``` ### Value + 函数定义 ```python def Value(self) -> str # 返回值 # 返回 str,Microsoft Active Accessibility 值属性 ``` ### 是否只读 + 函数定义 ```python def IsReadOnly(self) -> bool ``` ### 最大化 + 函数定义 ```python def Maximum(self) -> float ``` ### 最小化 + 函数定义 ```python def Minimum(self) -> float ``` ### 是否被选中 + 函数定义 ```python IsSelected(self) -> bool ``` ### 获取边界矩形 + 函数定义 ```python def GetBoundingRectangles(self) -> List[Rect] ``` ### 获取子类 + 函数定义 ```python def GetChildren(self) -> List['Control'] ``` ### 获取文本 + 函数定义 ```python def GetText(self, maxLength: int = -1) -> str ``` ### 移动 + 函数定义 ```python def Move(self, unit: int, count: int, waitTime: float = OPERATION_WAIT_TIME) -> int # 参数解析 unit: `TextUnit` 类中的一个值。 count: 要移动的文本单元的数量。正值将文本范围向前移动。负值将文本范围向后移动。零没有影响。 waitTime: 等待时间 ``` ## uiautomation API - 下 ### 获取光标位置 + 函数定义 ```python def GetCursorPos() -> Tuple[int, int] ``` ### 获取光标物理位置 + 函数定义 ```python def GetPhysicalCursorPos() -> Tuple[int, int] ``` ### win32gui按名称获取句柄 ```python import win32gui def getWin32Handler(classname=None, name=None) -> int: return win32gui.FindWindow(classname,name) ``` ### win32gui获取所有顶级窗口句柄 ```python import win32gui def getAllWin32TopHandlers() -> list: def callback(hwnd,param): if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd): param.append(hwnd) handlers = [] win32gui.EnumWindows(callback,handlers) return handlers ``` ### win32gui获取所有子窗口句柄 ```python import win32gui def getAllWin32ChildrenHandlers(HWND) -> list: if not HWND: return [] def callback(hwnd,param): param.append(hwnd) handlers = [] win32gui.EnumChildWindows(HWND,callback,handlers) return handlers ``` ### 切换窗口 + 函数定义 ```python def SwitchToThisWindow(handle: int) -> None ``` ### 是否顶级窗口 + 函数定义 ```python def IsTopLevelWindow(handle: int) -> bool ``` ### 是否窗口可见 + 函数定义 ```python def IsWindowVisible(handle: int) -> bool ``` ### 获取窗口文本 + 函数定义 ```python def GetWindowText(handle: int) -> str ``` ### 设置窗口文本 + 函数定义 ```python def SetWindowText(handle: int, text: str) -> bool ``` ### 获取编辑文本 + 函数定义 ```python def GetEditText(handle: int) -> str ``` ### 获取系统剪贴板当前具有的剪贴板格式 + 函数定义 ```python def GetClipboardFormats() -> Dict[int, str] ``` ### 获取父控件 + 函数定义 ```python def GetParentControl(self) -> 'Control' ``` ### 获取第一个子控件 + 函数定义 ```python def GetFirstChildControl(self) -> 'Control' ``` ### 获取最后一个子控件 + 函数定义 ```python def GetLastChildControl(self) -> 'Control' ``` ### 获取下一个兄弟控件 + 函数定义 ```python def GetNextSiblingControl(self) -> 'Control' ``` ### 获取先前的兄弟控件 + 函数定义 ```python def GetPreviousSiblingControl(self) -> 'Control' ``` ### 获取子控件 + 函数定义 ```python def GetChildren(self) -> List['Control'] ``` ### 设置全局搜索超时 + 函数定义 ```python def SetGlobalSearchTimeout(seconds: float) -> None ``` ### 显示桌面 + 函数定义 ```python def ShowDesktop(waitTime: float = 1) ``` ## 实操 ### case 1: 记事本插入一段文本并保存 #### 1. 启动记事本程序 ```python subprocess.Popen("notepad.exe") ``` #### 2. 选择主窗口 + 使用UI查看工具捕获窗口信息 ![image-20241122165914401](http://qiniu-dnypic-01.yunyunzhu.top/markdown_img/image-20241122165914401.png) + 获取主窗口 ```python mainWindow = auto.WindowControl(Name="无标题 - 记事本") ``` #### 3. 插入一段文本 + 打印子控件信息 ```python for o in mainWindow.GetChildren(): print(o) ``` + 子控件信息 ![image-20241122144344025](http://qiniu-dnypic-01.yunyunzhu.top/markdown_img/image-20241122144344025.png) + 插入文本 ```python edit = mainWindow.EditControl(Name="文本编辑器") edit.SendKeys("Hello UIAutomation") ``` #### 4. 保存 + ctrl + s 保存 ```python auto.SendKeys('{Ctrl}s') ``` + 此时会弹出另存为窗口,使用UI查看工具分析结构 ![image-20241122170413655](http://qiniu-dnypic-01.yunyunzhu.top/markdown_img/image-20241122170413655.png) + 获取另存为窗口 ```python saveWindow = mainWindow.WindowControl(Name="另存为") ``` + 设置保存文件名 ```python file = saveWindow.EditControl(Name="文件名:") file.SendKeys("report.txt") ``` + 触发保存操作 ```python saveBtn = saveWindow.ButtonControl(Name="保存(S)") saveBtn.Click() ``` #### 5. 完整代码 ```python import subprocess import uiautomation as auto def run(): # 打开记事本 subprocess.Popen("notepad.exe") # 获取主窗口 mainWindow = auto.WindowControl(Name="无标题 - 记事本") # 写入编辑内容 edit = mainWindow.EditControl(Name="文本编辑器") edit.SendKeys("Hello UIAutomation") # 触发保存流程 auto.SendKeys('{Ctrl}s') # 获取另存为窗口 saveWindow = mainWindow.WindowControl(Name="另存为") # 修改保存的文件名 file = saveWindow.EditControl(Name="文件名:") file.SendKeys("report.txt") # 保存文件 saveBtn = saveWindow.ButtonControl(Name="保存(S)") saveBtn.Click() if __name__=="__main__": run() ``` ### case 2: 获取微信通讯录列表 #### 1. 打开微信 ```python subprocess.Popen("D:\WeChat\WeChat.exe") ``` #### 2. 获取微信窗口 + 利用UI查看工具分析 ![image-20241122172637232](http://qiniu-dnypic-01.yunyunzhu.top/markdown_img/image-20241122172637232.png) + 获取主窗口 ```python wx = auto.WindowControl(searchDepth=1,Name="微信",ClassName="WeChatMainWndForPC") ``` #### 3. 点击通讯录 ```python friendButton = wxMainWindow.ButtonControl(Name="通讯录") friendButton.Click() ``` #### 4. 点击通讯录管理 ```python friendManagerButton = wxMainWindow.ButtonControl(Name="通讯录管理") friendManagerButton.Click() ``` #### 5. 鼠标移入通讯录管理窗口中心位置 ```python friendManagerWindow = auto.WindowControl(Name="通讯录管理",ClassName="ContactManagerWindow") friendManagerWindow.MoveCursorToMyCenter() ``` #### 6. 获取通讯录数据 ```python flag = True friends = [] number = 1 while flag: list = friendManagerWindow.ListControl(Name="") childrens = list.GetChildren() for item in childrens: nickName = item.TextControl().Name if nickName not in friends: print("""{}:{}""".format(number,nickName)) number+=1 friends.append(nickName) auto.WheelDown(waitTime=0.01) ``` #### 7. 完整代码 ```python import subprocess import uiautomation as auto import time def run(): # 打开微信 subprocess.Popen("D:\WeChat\WeChat.exe") # 定位到主窗口 wxMainWindow = auto.WindowControl(SearchDepth=1,ClassName="WeChatMainWndForPC",Name="微信") # 点击通讯录 friendButton = wxMainWindow.ButtonControl(Name="通讯录") friendButton.Click() # 点击通讯录管理 friendManagerButton = wxMainWindow.ButtonControl(Name="通讯录管理") friendManagerButton.Click() # 通讯录管理窗口 friendManagerWindow = auto.WindowControl(Name="通讯录管理",ClassName="ContactManagerWindow") friendManagerWindow.MoveCursorToMyCenter() flag = True friends = [] number = 1 while flag: list = friendManagerWindow.ListControl(Name="") childrens = list.GetChildren() for item in childrens: nickName = item.TextControl().Name if nickName not in friends: print("""{}:{}""".format(number,nickName)) number+=1 friends.append(nickName) auto.WheelDown(waitTime=0.01) if __name__=="__main__": run() ``` ### case 3: 获取微信聊天记录 (wxauto) ```python import time from wxauto import * def run(): # 实例化微信对象 wx = WeChat() # 指定监听目标 listen_list = [ '文件传输助手' ] for user in listen_list: wx.AddListenChat(who=user,savepic=True) while True: msgs = wx.GetListenMessage() print(msgs) time.sleep(5) if __name__=="__main__": run() ``` ### case 4: 获取微信聊天记录 (仿 wxauto) #### 1. 打开微信 ```python def openWechat(): subprocess.Popen("D:\WeChat\WeChat.exe") openWechat() ``` #### 2. 获取登录用户 ```python wx = auto.WindowControl(searchDepth=1,Name="微信",ClassName="WeChatMainWndForPC") loginUser = wx.ToolBarControl(Name="导航").GetChildren()[0].Name print("当前登录用户: {}".format(loginUser)) ``` #### 3. 切换到聊天列表 ```python wx.ToolBarControl(Name="导航").ButtonControl(Name="聊天").Click() ``` #### 4. 初始化监听对象 ```python def getHuihuaUser(wx,listenUser): openWechat() huihuaUser = None huihuaList = wx.ListControl(Name="会话") for o in huihuaList.GetChildren(): if (o.ControlType == auto.ControlType.ListItemControl and ( o.Name == listenUser or o.Name == listenUser + "已置顶")): huihuaUser = o return huihuaUser # 初始化监听对象 listenUsers = [ "文件传输助手" ] chatDict = dict() for listenUser in listenUsers: chatDict[listenUser] = dict() chatDict[listenUser]["name"] = listenUser chatDict[listenUser]["runtime_ids"] = [] # 打开会话窗口 for listenUser in listenUsers: # 判断会话窗口是否已经打开 huihuaWindowExists = auto.WindowControl(Name=listenUser).Exists(maxSearchSeconds=0.8) if not huihuaWindowExists: huihuaUser = getHuihuaUser(wx, listenUser) if not huihuaUser: # 输出搜索内容 search = wx.EditControl(Name="搜索") search.Click() # 分析字符中如果含有emoji标签,加上\uFE0E样式 searchListenUser = "" for s in listenUser: if emoji.is_emoji(s): searchListenUser += s + u'\uFE0E' else: searchListenUser += s # 设置粘贴板 auto.SetClipboardText(searchListenUser) # 发送复制指令 search.SendKeys('{Ctrl}v') # 搜索 wx.ListControl(Name="@str:IDS_FAV_SEARCH_RESULT:3780").ListItemControl(Name=listenUser).Click() huihuaUser = getHuihuaUser(wx, listenUser) # 双击打开会话窗口 huihuaUser.DoubleClick() ``` #### 5. 打开会话窗口 ```python for listenUser in listenUsers: # 判断会话窗口是否已经打开 huihuaWindowExists = auto.WindowControl(Name=listenUser).Exists(maxSearchSeconds=0.8) if not huihuaWindowExists: huihuaUser = getHuihuaUser(wx, listenUser) if not huihuaUser: # 输出搜索内容 search = wx.EditControl(Name="搜索") search.Click() # 分析字符中如果含有emoji标签,加上\uFE0E样式 searchListenUser = "" for s in listenUser: if emoji.is_emoji(s): searchListenUser += s + u'\uFE0E' else: searchListenUser += s # 设置粘贴板 auto.SetClipboardText(searchListenUser) # 发送复制指令 search.SendKeys('{Ctrl}v') # 搜索 wx.ListControl(Name="@str:IDS_FAV_SEARCH_RESULT:3780").ListItemControl(Name=listenUser).Click() huihuaUser = getHuihuaUser(wx, listenUser) # 双击打开会话窗口 huihuaUser.DoubleClick() ``` #### 6. 监听聊天数据 ```python def getMyRuntimeId(item): return ''.join([str(i) for i in item.GetRuntimeId()]) # 监听聊天数据 while True: msgDict = dict() for who in chatDict: msgs = [] chat = chatDict[who] # 首次填充消息id listUserWindow = auto.WindowControl(Name=who) msgList = listUserWindow.ListControl(Name="消息") if not chat["runtime_ids"]: for o in msgList.GetChildren(): chat["runtime_ids"].append(getMyRuntimeId(o)) chatDict[who] = chat # 取最新消息 newMsgItems = [] # 若当前消息的runtimeId不在chatDict的runtime_ids数组里,则输出消息数据并保存当前runtimeId到chatDict的runtime_ids数组 for o in msgList.GetChildren(): if getMyRuntimeId(o) not in chat["runtime_ids"]: newMsgItems.append(o) if newMsgItems: for newMsgItem in newMsgItems: chat["runtime_ids"].append( getMyRuntimeId(newMsgItem) ) chatDict[who] = chat # 消息内容 content = newMsgItem.Name nickName = "" if newMsgItem.GetChildren(): for o in newMsgItem.GetChildren()[0].GetChildren(): if o.ControlType == auto.ControlType.ButtonControl: nickName = o.Name excludeContents = ["以下为新消息", "查看更多消息"] if nickName and content and content in excludeContents and nickName==content: continue if not nickName and content and content in excludeContents: continue if nickName: if nickName == loginUser: msg = ["self", content, getMyRuntimeId(newMsgItem)] else: msg = [nickName, content, getMyRuntimeId(newMsgItem)] else: msg = ["SYS", content, getMyRuntimeId(newMsgItem)] msgs.append(msg) msgDict[who] = msgs # 发送提醒 if nickName and nickName !=loginUser: notification.notify( title="提醒", message=",".join(msg), app_name="我的应用", timeout=10, ticker="快捷提示" ) # 分析消息内容 if content == "[图片]": # 切换到会话窗口 listUserWindow.SwitchToThisWindow() # 触发图片点击,打开图片查看窗口 imgButtonControl = newMsgItem.ButtonControl(Name="") imgButtonControl.Click() # 触发保存流程 picViewWindow = auto.WindowControl(Name="图片查看") picViewWindow.ButtonControl(Name="另存为...").Click() # 保存 savePath = os.path.join(os.getcwd(), "微信文件", "微信图片_{}.jpg".format( datetime.datetime.now().strftime('%Y%m%d%H%M%S%f'))) if not os.path.exists(os.path.split(savePath)[0]): os.mkdir(os.path.split(savePath)[0]) saveWindow = picViewWindow.WindowControl(Name="另存为...") saveWindow.EditControl(Name="文件名:").SendKeys(savePath) time.sleep(1) saveWindow.ButtonControl(Name="保存(S)").Click() # 判断是否已存在,存在则覆盖 exists = saveWindow.PaneControl(Name="确认另存为").Exists(1) if exists: saveWindow.PaneControl(Name="确认另存为").ButtonControl(Name="是(Y)").Click() saveContent = "图片保存路径:{}".format(savePath) # 发送提醒 notification.notify( title="提醒", message=saveContent, app_name="我的应用", timeout=10, ticker="快捷提示" ) # 关闭图片查看窗口 picViewWindow.ButtonControl(Name="关闭").Click() print(msgDict) time.sleep(5) ``` #### 7. 完整代码 ```python import subprocess import time import os import datetime import emoji from plyer import notification import uiautomation as auto def openWechat(): subprocess.Popen("D:\WeChat\WeChat.exe") def getHuihuaUser(wx,listenUser): openWechat() huihuaUser = None huihuaList = wx.ListControl(Name="会话") for o in huihuaList.GetChildren(): if (o.ControlType == auto.ControlType.ListItemControl and ( o.Name == listenUser or o.Name == listenUser + "已置顶")): huihuaUser = o return huihuaUser def getMyRuntimeId(item): return ''.join([str(i) for i in item.GetRuntimeId()]) def run(): # 打开微信 openWechat() # 获取登录用户 wx = auto.WindowControl(searchDepth=1,Name="微信",ClassName="WeChatMainWndForPC") loginUser = wx.ToolBarControl(Name="导航").GetChildren()[0].Name print("当前登录用户: {}".format(loginUser)) # 切换到聊天列表 wx.ToolBarControl(Name="导航").ButtonControl(Name="聊天").Click() # 初始化监听对象 listenUsers = [ "文件传输助手" ] chatDict = dict() for listenUser in listenUsers: chatDict[listenUser] = dict() chatDict[listenUser]["name"] = listenUser chatDict[listenUser]["runtime_ids"] = [] # 打开会话窗口 for listenUser in listenUsers: # 判断会话窗口是否已经打开 huihuaWindowExists = auto.WindowControl(Name=listenUser).Exists(maxSearchSeconds=0.8) if not huihuaWindowExists: huihuaUser = getHuihuaUser(wx, listenUser) if not huihuaUser: # 输出搜索内容 search = wx.EditControl(Name="搜索") search.Click() # 分析字符中如果含有emoji标签,加上\uFE0E样式 searchListenUser = "" for s in listenUser: if emoji.is_emoji(s): searchListenUser += s + u'\uFE0E' else: searchListenUser += s # 设置粘贴板 auto.SetClipboardText(searchListenUser) # 发送复制指令 search.SendKeys('{Ctrl}v') # 搜索 wx.ListControl(Name="@str:IDS_FAV_SEARCH_RESULT:3780").ListItemControl(Name=listenUser).Click() huihuaUser = getHuihuaUser(wx, listenUser) # 双击打开会话窗口 huihuaUser.DoubleClick() # 监听聊天数据 while True: msgDict = dict() for who in chatDict: msgs = [] chat = chatDict[who] # 首次填充消息id listUserWindow = auto.WindowControl(Name=who) msgList = listUserWindow.ListControl(Name="消息") if not chat["runtime_ids"]: for o in msgList.GetChildren(): chat["runtime_ids"].append(getMyRuntimeId(o)) chatDict[who] = chat # 取最新消息 newMsgItems = [] # 若当前消息的runtimeId不在chatDict的runtime_ids数组里,则输出消息数据并保存当前runtimeId到chatDict的runtime_ids数组 for o in msgList.GetChildren(): if getMyRuntimeId(o) not in chat["runtime_ids"]: newMsgItems.append(o) if newMsgItems: for newMsgItem in newMsgItems: chat["runtime_ids"].append( getMyRuntimeId(newMsgItem) ) chatDict[who] = chat # 消息内容 content = newMsgItem.Name nickName = "" if newMsgItem.GetChildren(): for o in newMsgItem.GetChildren()[0].GetChildren(): if o.ControlType == auto.ControlType.ButtonControl: nickName = o.Name excludeContents = ["以下为新消息", "查看更多消息"] if nickName and content and content in excludeContents and nickName==content: continue if not nickName and content and content in excludeContents: continue if nickName: if nickName == loginUser: msg = ["self", content, getMyRuntimeId(newMsgItem)] else: msg = [nickName, content, getMyRuntimeId(newMsgItem)] else: msg = ["SYS", content, getMyRuntimeId(newMsgItem)] msgs.append(msg) msgDict[who] = msgs # 发送提醒 if nickName and nickName !=loginUser: notification.notify( title="提醒", message=",".join(msg), app_name="我的应用", timeout=10, ticker="快捷提示" ) # 分析消息内容 if content == "[图片]": listUserWindow.SwitchToThisWindow() # 触发图片点击,打开图片查看窗口 imgButtonControl = newMsgItem.ButtonControl(Name="") imgButtonControl.Click() # 触发保存流程 picViewWindow = auto.WindowControl(Name="图片查看") picViewWindow.ButtonControl(Name="另存为...").Click() # 保存 savePath = os.path.join(os.getcwd(), "微信文件", "微信图片_{}.jpg".format( datetime.datetime.now().strftime('%Y%m%d%H%M%S%f'))) if not os.path.exists(os.path.split(savePath)[0]): os.mkdir(os.path.split(savePath)[0]) saveWindow = picViewWindow.WindowControl(Name="另存为...") saveWindow.EditControl(Name="文件名:").SendKeys(savePath) time.sleep(1) saveWindow.ButtonControl(Name="保存(S)").Click() # 判断是否已存在,存在则覆盖 exists = saveWindow.PaneControl(Name="确认另存为").Exists(1) if exists: saveWindow.PaneControl(Name="确认另存为").ButtonControl(Name="是(Y)").Click() saveContent = "图片保存路径:{}".format(savePath) print(saveContent) # 发送提醒 notification.notify( title="提醒", message=saveContent, app_name="我的应用", timeout=10, ticker="快捷提示" ) # 关闭图片查看窗口 picViewWindow.ButtonControl(Name="关闭").Click() print(msgDict) time.sleep(5) if __name__=="__main__": run() ``` ## 参考文献 1. [初识UI自动化](https://download.csdn.net/blog/column/11830334/124297008) 2. [Emoji的编码以及常见问题处理](https://segmentfault.com/a/1190000007594620) 3. [Emoji Unicode 参考手册](https://www.w3school.com.cn/charsets/ref_emoji.asp) 4. [wxauto](https://github.com/cluic/wxauto) # Selenium ## 前言 ### Selenium是什么 > Selenium是一个用于自动化web应用程序测试的工具。它提供了一组工具和库,可以用多种编程语言(如Java、Python、C#等)编写测试脚本,模拟用户在浏览器中的行为,如点击链接、填写表单、提交数据等。Selenium可以在各种浏览器上运行,包括Chrome、Firefox、Safari等,它还可以与其他测试框架和工具集成,帮助开发人员和测试人员自动化执行各种测试任务,提高测试效率和质量 > > ### 浏览器驱动说明 > 以下所有的试验代码都是基于chromedriver这个驱动实现的 > > ## 环境准备 + Python 3.7.9 + chromedriver + selenium ## Selenium安装 ```shell pip3 install selenium ``` ## 浏览器驱动安装 ### 目前支持的浏览器 | 浏览器 | 驱动安装地址 | | :-----: | :----------------------------------------------------------: | | Chrome | https://chromedriver.chromium.org/downloads | | Edge | https://developer.microsoft.com/microsoft-edge/tools/webdriver/ | | Firefox | https://github.com/mozilla/geckodriver/releases | | Safari | https://developer.apple.com/documentation/webkit/testing-with-webdriver-in-safari | ### 安装Chrome浏览器驱动 + 地址栏输入以下路径, 查看浏览器版本 ``` chrome://settings/help ``` ![image-20241203104651473](http://qiniu-dnypic-01.yunyunzhu.top/markdown_img/image-20241203104651473.png) + 我的版本是最新的, 所以去[这里](https://googlechromelabs.github.io/chrome-for-testing/)下载最新稳定版本的驱动 ![image-20241203105100051](http://qiniu-dnypic-01.yunyunzhu.top/markdown_img/image-20241203105100051.png) + 下载解压之后要配置环境变量 ![image-20241203105329352](http://qiniu-dnypic-01.yunyunzhu.top/markdown_img/image-20241203105329352.png) ## Selenium的初始化 + 代码 ```python from selenium import webdriver def run(): browser = webdriver.Chrome() browser.get("https://www.baidu.com") browser.quit() if __name__=="__main__": run() ``` + 运行效果 ![image-20241203110238181](http://qiniu-dnypic-01.yunyunzhu.top/markdown_img/image-20241203110238181.png) ## 参考文献 1. [Selenium快速上手](https://blog.csdn.net/Pan_peter/article/details/139360501) 2. [Selenium基础入门及实践](https://www.jianshu.com/p/1531e12f8852)