前提条件
- Windows 10或者更新版本
- 需要WinAppDriver
环境搭建
- 打开Windows PC的开发者模式
- 下载Windows SDK并默认安装
- 下载Windows driver并默认安装
- 运行
WinAppDriver.exe
(记得要用admin权限运行), 默认路径 (C:\Program Files (x86)\Windows Application Driver
)
可以自定义地址或端口:
1 | WinAppDriver.exe 4727 |
如下图:
Windows 自动化脚本
运行脚本前要打开 WinAppDriver.exe
对于Windows App来说,只需要传一个app
capabilities 即可。
对于UWP的App,app
对应的值为Application Id(App ID)。关于如何获取APP ID,可以使用powershell命令get-StartApps
来获取,打开powershell终端运行:get-StartApps | select-string "计算器"
即可获取值(运行命令之前先打开计算器)。以下是java样例代码:
1 | DesiredCapabilities cap = new DesiredCapabilities(); |
对于经典的Windows App,app
对应的值为可执行的.exe
文件路径。以下是java样例代码:
1 | // Launch Notepad |
Windows定位元素
使用Windows SDK提供的工具inspect.exe
(C:\Program Files (x86)\Windows Kits\10\bin\x86
或者C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x64
根据系统查看)来定位,详情查看inspect,或者使用AccExplorer32、UISpy定位。
支持的定位方式:
API | 定位方法 | 对应inspect.exe的属性 | 例子 |
---|---|---|---|
FindElementByAccessibilityId | accessibility id | AutomationId | AppNameTitle |
FindElementByClassName | class name | ClassName | TextBlock |
FindElementById | id | RuntimeId (decimal) | 42.333896.3.1 |
FindElementByName | name | Name | Calculator |
FindElementByTagName | tag name | LocalizedControlType (upper camel case) | Text |
FindElementByXPath | xpath | Any | //Button[0] |
计算器的例子
Python(GitHub):
1 | import unittest |
java(GitHub):
1 | import org.openqa.selenium.WebElement; |
参考
- http://appium.io/docs/en/drivers/windows/
- https://github.com/Microsoft/WinAppDriver?WT.mc_id=-blog-scottha
问题总结
org.openqa.selenium.WebDriverException: Failed to locate opened application window with appId
遇到此问题是在启动APP时报的错,成功的启动了APP,但是抛出这个异常,导致后续无法测试,目前找了一个临时解决方案:在new driver
时增加try catch
机制,即可避免,例如:
1 | try { |