appium支持5种定位方式:
- 通过元素ID定位:resource-id
- 通过CLASS_NAME:class
- 通过ACCESSIBILITY_ID:content-desc
- 通过ANDROID_UIAUTOMATOR定位
- 通过XPATH定位
与UI自动化恰恰相反,我们在app自动化中并不推荐采用XPATH方式进行定位,因为其性能较差。
在app自动化中我们最优选择采用 ID、CLASS_NAME、ACCESSIBILITY_ID这三种方式
但在实际实施过程中,因为开发同学不规范等以上三种方式经常无法实现其唯一性,所以我们在编写脚本的时候最常用的是ANDROID_UIAUTOMATOR这种定位方式,该方式支持元素上所有的属性条件(下图Node Detail部分)。
因为该种方式基于uiautomator框架实现需调用其java实现的APIs,实际编写不够友好。
本文仅枚举几个在实际使用中常用的方法,其余方法需要各位在官方文档中自行查阅
方法 | 描述 |
---|---|
resourceId | resourceId(可用ID方法代替) |
resourceIdMatches | 正则匹配ID |
text | 绝对匹配文本(Node Detail中text属性) |
textContains | 包含文本 |
textMatches | 正则匹配文本 |
textStartsWith | 开头匹配文本 |
官方文档:https://developer.android.com/reference/android/support/test/uiautomator/UiSelector.html
image.png
image.png
from appium import webdriver
from appium.webdriver.common.mobileby import Mobileby
caps = "设备信息" # demo 具体值不展示
driver = webdriver.Remote(desired_capabilities=caps)
# ID
driver.find_element(Mobileby.ID, "resource-id") # 较常出现空值的现象
# CLASS_NAME
driver.find_element(Mobileby.CLASS_NAME, "android.widget.TextView") # app中class更倾向于web中type,非web中class。实际实施中基本无法使用,相同值过多
# ACCESSIBILITY_ID
driver.find_element(Mobileby.ACCESSIBILITY_ID, "当前所在页面,搜一搜") # 较常出现空值,如果有能力推动最好让开发加上
# xpath
driver.find_element(Mobileby.XPATH, "//android.widget.FrameLayout[@content-desc='当前所在页面,搜一搜']")
# ANDROID_UIAUTOMATOR
driver.find_element(Mobileby.ANDROID_UIAUTOMATOR, 'new UiSelector().description("当前所在页面,搜一搜")')
driver.find_element(Mobileby.ANDROID_UIAUTOMATOR, 'new UiSelector().text("复制")') # 因为手机屏幕较小,信息量比较少。故一般在实际使用的时候较多用text用于定位,一般不会出现重复的现象