使用过 Appium 的都知道,元素的定位方式有不少种,具体使用哪种,主要看业务的须要和本身的使用爱好。下面总结一下,Appium 到底有哪些定位方式,定位的元素如下面截图指定的元素为例子:android
这里给 Macaca 的 inspector 查看器打个广告,的确很好用,有须要可到社区的 Macaca 版块本身查找啊!git
我说的定位方式都是基于我本身亲测过,没使用或比较少用的就在这里不列举了,若有错误的地方,请多多包涵!经常使用的定位方式(仅限 Android 和 iOS 两种系统)有 className、id、xpath、AccessibilityId、AndroidUIAutomator、iOSNsPredicateString、iOSClassChain、IosUIAutomation等github
使用元素的className
属性定位,支持:Android 和 iOS,推荐使用。MobileBy.className("XCUIElementTypeButton")
app
使用元素的Resource Id
属性定位,支持:Android,仅支持 Android 4.3或以上,推荐使用。反正我没有在 iOS 用过,你们有正确使用过的例子,能够分享一下。MobileBy.id("package.name:id/android")
框架
支持:Android 和 iOS。但因为 iOS 10开始使用的 XCUITest 框架原声不支持,定位速度很慢,因此官方如今不推荐你们使用,也有其余替代的定位方式可以使用。ui
使用绝对路径定位,如截图所显示的 xpath 路径spa
`MobileBy.xpath("className/className/className/className")`
使用相对路径定位code
`MobileBy.xpath("//className")`
经过元素的索引定位blog
`MobileBy.xpath("//className[index]")`
经过元素的属性定位索引
一种属性:`MobileBy.xpath("//className[@label='更多信息']")` 两种属性:`MobileBy.xpath("//className[@label='更多信息'][@isVisible='1']")` 部分属性(最强大):`MobileBy.xpath("//className[contains(@label,'更多')]")`
替代之前的name
定位方式,推荐使用。
在 Android 上,主要使用元素的content-desc属性
,如该属性为空,不能使用此定位方式。
在 iOS 上,主要使用元素的label
或name
(两个属性的值都同样)属性进行定位,如该属性为空,如该属性为空,也是不能使用该属性。MobileBy.AccessibilityId("更多信息")
仅支持 Android 4.2或以上,可支持元素的单个属性和多个属性定位,推荐使用。
一种属性:MobileBy.AndroidUIAutomator("new UiSelector().text(\"发送\")")
两种属性:MobileBy.AndroidUIAutomator("new UiSelector().text(\"发送\").clickable(true)")
元素的全部属性均可用作定位,功能很是强大,且速度很快。
仅支持 iOS 10或以上,可支持元素的单个属性和多个属性定位,推荐使用。
一种属性:MobileBy.iOSNsPredicateString("type == 'XCUIElementTypeButton'")
两种属性:MobileBy.iOSNsPredicateString("type == 'XCUIElementTypeButton' AND label == '更多信息'")
具体 iOSNsPredicate语法结构可查看官方文档,或期待我下一个帖子。
仅支持 iOS 10或以上,这是 github 的 Mykola Mokhnach 大神开发,仅限在 WebDriverAgent 框架使用,用于替代 xpath 的,但使用一阵子后,感受灵活性没有 xpath 和 iOSNsPredicate 好,应该还不完善吧。具体使用方法,请见:https://github.com/appium/app... 。MobileBy.iOSClassChain('XCUIElementTypeWindow[1]/XCUIElementTypeOther[1]/XCUIElementTypeOther[1]/XCUIElementTypeNavigationBar[1]/XCUIElementTypeOther[1]/XCUIElementTypeButton[2]')
仅支持 iOS 19.3或如下,是 iOS 旧框架 UIAutomation 的定位方式,如今基本上不多使用
总结:以上这个多定位方式,不多说所有用完。根据个人经验,推荐使用:Android:AndroidUIAutomator > className = id = AccessibilityId > xpath。iOS:iOSNsPredicateString > className = AccessibilityId