【问题标题】:xPath for listing element in android (using appium automation)用于在 android 中列出元素的 xPath(使用 appium 自动化)
【发布时间】:2017-09-01 02:35:54
【问题描述】:

我在 Android 应用中有一个可滚动列表(搜索结果),对于 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 inspector提供)是这样的:

//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]/android .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]/android .widget.TextView[1]

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

【问题讨论】:

  • 你能提供最后一个TextView..properties在appium检查器中显示的详细信息
  • @sai 更新信息
  • 查看答案

标签: android selenium xpath appium


【解决方案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

【讨论】:

    【解决方案2】:

    您可以使用 id 来代替 XPath。

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

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

    与 id 相比,XPath 将花费更多时间来识别元素。

    【讨论】:

    • 我以前试过。问题是我有多个具有相同 ID 的结果。因此,如果我使用它,它将返回多个结果(# 可能会有所不同)。 xPath 似乎更好,因为我可以根据需要选择第一个或第二个结果。
    • 那么你可以使用 driver.findElements(By.id("com.abc.xyz.debug:id/student_label_text")).get(0) 来获得第一个。像这样你可以这样做而不是 xpath。因为 xpath 是不可取的
    猜你喜欢
    • 2016-10-08
    • 2017-08-03
    • 2018-03-15
    • 2014-11-27
    • 2020-04-25
    • 1970-01-01
    • 2019-10-05
    • 2014-10-27
    • 2016-08-23
    相关资源
    最近更新 更多