一、前言大家好,我是安国!说到自动化,大家可能会想到App端的Appium、Airtest、AutoJS,或者是Selenium、Puppeteer、Cypress等web端的自动化框架。在这篇文章中,我将和大家聊一聊PC端的自动化工具——WinAppDriver2。准备WinAppDriver,全称WindowsApplicationDriver,是一个类似Windows上Selenium的UI自动化驱动服务框架。支持Appium,可以使用Appium-Python-Client依赖库完成Windows桌面程序的自动化。项目地址:https://github.com/Microsoft/...需要注意的是,使用WinAppDriver服务框架完成Windows自动化,需要满足Windows10或WindowsServer2016及以上版本要求。另外,它支持的应用程序包括:UWP——UniversalWindowsPlatformWinForms——WindowsFormsWPF——WindowsPresentationFoundationWin32——在实施ClassicWindows之前,我们需要做以下准备工作2-1打开“开发者模式”关键字搜索“DeveloperSettings”》,选择打开“开发者模式”2-2安装窗口组件元素识别工具常用的两个窗口元素识别工具是:inspect.exe、FlaUInspect,作为官方的组件元素识别工具,集成了inspect.exe在WindowsSDK中。如果本地没有该文件,可以通过以下链接安装https://download.microsoft.co...相比inspect.exe,FlaUInspect界面更简单,功能更易用(推荐)Project地址:https://github.com/FlaUI/FlaU...2-3通过以下链接安装WinAppDriver下载WinAppDriver应用程序并在本地运行https://github.com/Microsoft/...2-4构建Appium环境部分内容涉及到NodeJS的安装和Appium-Server环境的搭建可以参考:https://www.cnblogs.com/amoys...2-5安装依赖最后安装Python依赖库Appium-Python-Client#安装依赖Appium-Python-Clientpip3安装Appium-Python-Client3。下面以在PC端操作微信为例,说说自动化的常用步骤。首先,我们在本地开启WinAppDriver服务,让它在后台运行。然后,我们通过PC版微信的ip地址、端口号和绝对路径用Python编写自动化脚本,使用Appium打开微信导入时间,osfromappiumimportwebdriverfromselenium.webdriverimportActionChainsfromselenium.webdriver.common.keysimportKeysfrom时间importsleepclassAuto():defopen_weixin(self,host='localhost',port=4723):#开启WinAppDriver服务#注意:如果手动开启,可以注释掉#os.system(r'start""/d"C:\ProgramFiles\WindowsApplicationDriver\""WinAppDriver.exe"')#配置信息#包含:平台名称、系统、应用程序绝对路径desired_caps={'platformName':'Windows','deviceName':'WindowsPC','app':r"D:\ProgramFiles(x86)\Tencent\WeChat\WeChat.exe"}try:#连接WinAppDriver服务,打开目标软件self.driver=webdriver.Remote('http://{}:{}'.format(host,port),desired_caps)exceptExceptionase:raiseAssertionError(e)接下来通过“组件元素识别工具”获取界面元素的属性"value,执行点击、移动、滑动等常用操作例如:点击“文件传输助手”发送消息#给文件传输助手发送消息defsend_msg(self,element_name,msg):""":paramelement_name:元素名称value:parammsg:::return:"""#通过name属性查找目标元素chat_element=self.weixin_driver.find_element_by_name(target_name)#点击元素进入聊天界面chat_element.click()#找到输入框,输入self.weixin_driver.find_element_by_name("input").send_keys(msg)#点击右下角的send,发送一条消息出去self.weixin_driver.find_element_by_name("send(S)").click()需要注意的是,如果界面涉及到滑动,可以使用"ActionChains"移动鼠标,然后使用win32api和win32con模拟屏幕滑动importwin32apiimportwin32confromappiumimportwebdriverfromselenium.webdriverimportActionChains#模拟屏幕滑动#1.移动到一个元素区域ActionChains(self.weixin_driver).move_to_element(self.weixin_driver.find_element_by_name("element_name")).perform()#2.滑动界面#例如向上滚动模拟滑动win32api.mouse_event(win32con.MOUSEEVENTF_WHEEL,0,0,-500)自动运行完成后,可以主动释放资源,关闭WinAppDriver服务#释放资源,关闭服务deftearDownFunc(self):print("Readytoexit")sleep(2)#1.释放资源self.weixin_driver.quit()#2.关闭WinAppDriver应用os.system('@taskkill/f/imWinAppDriver.exe')4.最后在实际使用过程中,你可能会遇到复杂的桌面应用,这时候我们可以通过打印driver对象的“page_source”元素来控制树的值,从而帮助我们快速定位元素,进而完善自动化脚本。如果觉得文章还不错,请点赞、分享和留言,因为这将是我继续输出更多优质文章的最强大动力!
