appium元素定位方式

Appium元素定位方法介绍及应用:
通过上面两种工具,可以获取元素的相关信息;在appium中提供了一系列
的元素定位API,通过在这些API中输入指定的元素信息,就能完成元素定位,
定位元素后就进行对元素进行自动操作。


基本元素定位API如下:
1、ID定位(取resource-id、id、name)
driver.find_element_by_id('')
2、class定位(取class)
driver.find_element_by_class_name('')
3、AccessibilityId定位(取content-desc)
driver.find_element_by_accessibility_id('')
备注:其中name方式(取text)已不支持

Xpath定位方法:

1、绝对路径:
元素的全路径,包含了全部节点。这种方法写起来很长,效率不高;另一
方面由于涉及到太多层,一旦中间任何一层有变动,那元素就定位不到了

2、使用 属性 定位:
text属性:
driver.find_element_by_xpath('//类名[@text=text值]')
resource-id属性:
driver.find_element_by_xpath('//类名[@resource-id=属性值]')
content-desc属性:
driver.find_element_by_xpath('//类名[@content-desc=属性值]')
class属性:
driver.find_element_by_xpath('//类名')
多属性:and 表示并且 or表示或者
driver.find_element_by_xpath('//类名[@属性名=属性值 and/or @属性名=属性
值]')
备注:
1、所有元素的属性都可以进行定位,但必须该属性的值是界面上唯一的
2、xpath支持 * 代表任意个字符 ,比如find_element_by_xpath('//*[@text=text
值]') ,这种用法容易同时识别多个元素

3、使用 部分属性内容 定位:
当元素的属性值过长或者元素属性值内容中存在动态变化的情况下,可以使
用该方法。
起始位置匹配:starts-with()
driver.find_element_by_xpath('//类名[starts-with(@属性名,部分属性值)]')
包含匹配:contains()
driver.find_element_by_xpath('//类名[contains(@属性名,部分属性值)]')
末尾位置匹配:ends-with()
driver.find_element_by_xpath('//类名[ends-with(@属性名,部分属性值)]')

uiautomator方法定位app元素:
appium在android端是调用其底层的UIAutomator2自动化测试框架去驱动自
动化,在定位元素的时候,可以借助UIAutomator2的语法来实现定位。在代码
实现上提供的API是find_element_by_android_uiautomator。
1、根据text定位:
find_element_by_android_uiautomator('text("值")')
find_element_by_android_uiautomator('new UiSelector().text("值")')
text定位相关函数:
textContains:模糊匹配文本
textStartsWith:以某个文本开头来匹配
textMatches:正则匹配

2、根据resourceId定位:
find_element_by_android_uiautomator('resourceId("值")')
find_element_by_android_uiautomator('new UiSelector().resourceId("值")')
3、根据className定位: 关键字 className
4、根据contenet-des定位: 关键字 description
5、组合定位(类名和文本):
new UiSelector().className("类名").text("值")
其它组合定位方式类推

6、根据元素关系定位:
1)后代元素定位
使用条件:子元素属性不定,不唯一,只能通过父元素来定位
new UiSelector().resourceId("值").childSelector(className("值").instance(数字))

解释:
其中childSelector可以传入resourceId、description等方法,instance表示匹配的结果所有元素里面的第几个元素,从0开始计数

new UiSelector().resourceId("父元素的属性值").childSelector(className("被定位的子元素元素的属性值").instance(索引))


2)兄弟元素定位
通过子元素找到父元素,然后通过父元素再去找兄弟元素
new UiSelector().resourceId("值").fromParent(text("值"))

解释:new UiSelector().resourceId("子元素属性值").fromParent(text("兄弟元素的属性值(定位的元素的属性值)"))

fromParent()表示从元素的父元素下查找

posted @ 2020-08-07 10:52  joy小羲  阅读(406)  评论(0编辑  收藏  举报