博客首发
前提条件
- Windows 10或者更新版本
- 需要WinAppDriver
环境搭建
-
打开Windows PC的开发者模式
-
下载Windows SDK并默认安装
-
下载Windows driver并默认安装
-
运行
WinAppDriver.exe
(记得要用admin权限运行), 默认路径 (C:\Program Files (x86)\Windows Application Driver
)
可以自定义地址或端口:WinAppDriver.exe 4727 WinAppDriver.exe 127.0.0.1 4725 WinAppDriver.exe 127.0.0.1 4723/wd/hub
如下图:
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样例代码:
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability("app", "LexisNexisAPAC.LexisRed_wsek3cqrhvvz2!App");
driver = new WindowsDriver(new URL("http://127.0.0.1:4723"), cap);
driver.findElementByAccessibilityId("CalculatorResults");
对于经典的Windows App,app
对应的值为可执行的.exe
文件路径。以下是java样例代码:
// Launch Notepad
DesiredCapabilities cap= new DesiredCapabilities();
cap.SetCapability("app", "C:\\Windows\\System32\\notepad.exe");
cap.SetCapability("appArguments", "MyTestFile.txt");
cap.SetCapability("appWorkingDir", "C:\\MyTestFolder");
driver= new WindowsDriver(new URL("http://127.0.0.1:4723"), cap);
// Use the session to control the app
driver.FindElementByClassName("Edit").SendKeys("This is some text");
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):
import unittest
from appium import webdriver
class WindowsCalculatorTest(unittest.TestCase):
@classmethod
def setUpClass(self):
# set up appium
desired_caps = {
}
desired_caps["app"] = "Microsoft.WindowsCalculator_8wekyb3d8bbwe!App"
self.driver = webdriver.Remote(command_executor='http://127.0.0.1:4723', desired_capabilities=desired_caps)
@classmethod
def tearDownClass(self):
self.driver.quit()
def getresults(self)