Xpath定位-高级定位

发布时间 2023-04-09 16:37:59作者: 三天乐趣

Xpath语法:https://www.w3school.com.cn/xpath/xpath_syntax.asp

包含-contains()

  • Xpath 表达式中的一个函数
  • contains()函数匹配==属性值==中包含的==字符串== //*[contains(@属性,"属性值")]
  • contains() 函数定位的元素很容易为 list
  • contains() 函数内的属性名需要用 @开始

Xpath轴

1、父子

当前节点的父节点

//*[@text="HK"]/..

//*[@text="HK"]/parent::*

当前节点的子节点

//*[@resource-id="resource-id"]/child::*

2、爷孙

当前节点的爷爷

//*[@text="HK"]/../..

//[@text="HK"]/parent::/parent::*

当前节点的孙子

//*[@resource-id="resource-id"]/child::*/child::*

3、祖先

返回当前节点的所有祖先

//*[@text="HK"]/ancestor::android.widget.RelativeLayout

显式指定要返回的祖先

//*[@text="HK"]/ancestor::android.widget.RelativeLayout[1]

4、兄弟姐妹

1)节点后的兄弟姐妹节点:following-sibling

选择当前节点之后的所有兄弟节点

  • 节点后有一个兄弟节点 

//*[@text="HK"]/following-sibling::*

  • 节点后有多个兄弟节点 

//*[@resource-id="resource-id"]/following-sibling::*[@resource-id="resource-id"]

2)节点前的兄弟姐妹节点:preceding-sibling

选择当前节点之前的所有兄弟节点

  • 节点前有一个兄弟节点 

//*[@text="09988"]/preceding-sibling::*

  • 节点前有多个兄弟节点

//*[@resource-id="resource-id"]/preceding-sibling::*[@resource-id="resource-id"]

Xpath 运算符

1、AND

  • 可以在 XPath 表达式中放置 2 个条件
  • 在 AND 两个条件都应该为真的情况下,才能找到元素 
  • //*[@resource-id="resource-id" and @text="107.8"]

2、OR

  • 可以在 XPath 表达式中放置 2 个条件

  • 在 OR 的情况下,两个条件中的任何一个为真,就可找到元素。

  • OR 定位获取的是并集

  • //*[@resource-id="resource-id" or @text="加自选"]

uiautomator定位

  Android独有的定位方式,一般不使用 uiautomator 定位,在要求定位速度的时候使用。

优点:

  • xpath定位速度慢
  • uiautomator是android的工作引擎,速度快

缺点:

  • 表达式书写复杂,容易写错IDE没有提示

1、定位方式

  • 通过resourceid定位:new UiSelector.resourceId("Id")
  • 通过classname定位:new UiSelector.className("className")
  • 通过content-desc定位:new UiSelector.description("content-desc属性")
  • 通过文本定位:

    用法:driver.find_element_by_android_uiautomator(表达式).click()

    通过text文本定位语法:new UiSelector.text("text文本")

    如果文本比较长,可以使用 textContains 模糊匹:new UiSelector.textContains("包含text文本")

    同样可以用 textStartsWith 是以某个文本开头来匹配:new UiSelector.textStartsWith("以text文本开头")

    也可以用正则表达式 textMatches 匹配:new UiSelector.textMatches("正则表达式")

2、uiautomator 组合定位

  • id 与 text 属性组合

id_text = 'resourceId("resourceId").text("text")'

driver.find_element_by_android_uiautomator(id_text).click()

  • class 与 text 属性组合

class_text = 'className("className").text("text")'

driver.find_element_by_android_uiautomator(class_text).click()

3、父子关系定位 childSelector

son = 'resourceId("resourceId").childSelector(text("text"))'

4、兄弟定位 fromParent

brther = 'resourceId("resourceId").fromParent(text("text"))'

5、实时滚动查找元素

scroll_text = 'new UiScrollable(new UiSelector().scrollable(true).instance(0))

.scrollIntoView(new UiSelector.text("text文本").instance(0));'

driver.find_element_by_android_uiautomator(scroll_text).click()

 

笔记2023-4-9