xPath for android中的列表元素(使用appium自动化)

时间:2017-04-06 07:44:27

标签: android selenium xpath appium

我在Android App中有一个可滚动列表(搜索结果),对于Appium自动化,我需要从中选择一个特定的元素。 Appium检查员提供索引,资源ID和xpath等信息。

content-desc:
type: android.widget.TextView
text: AMI
index: 0
enabled: true
location: {60, 513}
size: {81, 61}
checkable: false
checked: false
focusable: false
clickable: false
long-clickable: false
package: com.abc.xyz.debug
password: false
resource-id: com.abc.xyz.debug:id/student_label_text
scrollable: false
selected: false

第一个结果的xPath(由appium检查员提供)是这样的:

  

// android.support.v7.widget.RecyclerView [1] /android.widget.FrameLayout [1] /android.widget.FrameLayout [1] /android.widget.LinearLayout [1] /android.widget.LinearLayout [1] /android.widget.LinearLayout [1] /android.widget.FrameLayout [1] /android.widget.RelativeLayout [1] /android.widget.LinearLayout [1] /android.widget.LinearLayout [1] /机器人.widget.TextView [1]

第二个结果是......

  

// android.support.v7.widget.RecyclerView [1] /android.widget.FrameLayout [2] /android.widget.FrameLayout [1] /android.widget.LinearLayout [1] /android.widget.LinearLayout [1] /android.widget.LinearLayout [1] /android.widget.FrameLayout [1] /android.widget.RelativeLayout [1] /android.widget.LinearLayout [1] /android.widget.LinearLayout [1] /机器人.widget.TextView [1]

以上xPaths工作,但我正在寻找更短的版本。我尝试了各种组合,但因为我是新手,所以无法找出解决方案。有关这个或任何可以完成这项工作的工具的任何帮助吗?

2 个答案:

答案 0 :(得分:1)

而不是XPath,你可以正确使用id。

使用xpath将影响我们脚本的执行速度。我们可以使用如下所示的id:

driver.findElement(By.id("student_label_text"))

与id相比,XPath需要花费很多时间来识别元素。

答案 1 :(得分:1)

使用Xpath的最佳选择通常是在元素的任何属性中查找唯一值。从示例值中,您可以通过文本值找到:

driver.findElement(By.xpath("//android.widget.TextView[@text='AMI']"));

由于xpath比其他查找策略慢,您可以首先获取与id匹配的所有元素,然后检查这些元素具有哪些属性值:

List<MobileElement> elements = driver.findElements(By.id("com.abc.xyz.debug:id/student_label_text"));
for (MobileElement element : elements) {
    if (element.getAttribute("text") == "AMI") {
        element.click();
    }
}

请注意,我使用findElements而不是findElement来获取所有匹配元素的列表。

getAttribute命令的用法没有很好的记录。需要一些挖掘来找出所有可接受的属性名称:

https://github.com/appium/appium-android-bootstrap/blob/master/bootstrap/src/io/appium/android/bootstrap/AndroidElement.java#L182

https://github.com/appium/appium-android-bootstrap/blob/master/bootstrap/src/io/appium/android/bootstrap/AndroidElement.java#L94