Appium Android 端元素定位

环境

  • jdk 1.8

  • io.appium 6.1.0

官方文档

https://github.com/appium/appium/blob/master/docs/en/commands/element/find-elements.md

下面介绍的定位是官方文档能查到的

定位方式

findElementByName

新版本name不能定位Name错误日志

org.openqa.selenium.InvalidSelectorException: Locator Strategy 'name' is not supported for this session (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds

在driver.js文件中locatorStrategies数组中没有name

this.locatorStrategies = ['xpath', 'id', 'class name', 'accessibility id', '-android uiautomator'];

新版本不推荐用这个方式,应该被废弃了

findElementById

页面中resource-id属性,id可以简写,appium会尝试定位

id定位用的最多

findElementById("agree")

findElementByClassName

页面中的class属性,适合class名字只有一个

findElementByClassName("android.widget.Button")

findElementByXPath

这个方法适合id的时候用,xpath定位相对较慢

xpath定位比较灵活,但是需要手写,有一定难度

通过text定位

findElementByXPath("//android.widget.TextView[contains(@text,'Search')]")

通过序列定位

findElementByXPath("//android.widget.TextView[contains(@index,0)]")


findElementByAccessibilityId

AccessibilityId对应的是content-desc

页面中不一定有这个属性

findElementByAccessibilityId("App")

findElementByAndroidUIAutomator


这个方法应该UIAutomator2新增的一个底层方法,appium较新版本才有

App是控件text属性vlaue

findElementByAndroidUIAutomator("new UiSelector().text(\\"App\\")")

定位方式选择

  • 没有一种定位方式是万能的,实际项目需要多种定位结合使用

  • id > AndroidUIAutomator > AccessibilityId > XPath > ClassName