【问题标题】:How to merge 2 xpath in one如何将2个xpath合并为一个
【发布时间】:2018-04-26 22:56:11
【问题描述】:

HTML

<li class="wdappchrome-ai" data-automation-id="searchInputAutoCompleteResult" tabindex="-2" aria-posinset="1" aria-setsize="3">
<span data-automation-id="searchInputAutoCompleteResultFullText">
    <span style="font-weight:500">
        <span data-automation-id="searchInputAutoCompleteResultToken" style="font-weight:400">mike</span>
        <span data-automation-id="searchInputAutoCompleteResultToken" style="font-weight:400">diana</span>
    </span>
</span>
</li>

我将用户全名划分为spans,所以我想构建 xpath,它返回我从单个 list 组合两个/多个跨度的文本。

目前我正在使用 2 个或更多基于用户名的 xpath,分为跨度。

我使用://li[.//span[text()='mike']]//li[.//span[text()='diana']]

然后我在语法上使用 java 为上面的 xpath 和合并执行gettext()。所以我正在寻找解决方案,它可以在上面的特定li 标记内为我提供所有span 的全文。

【问题讨论】:

    标签: java html xpath selenium-webdriver


    【解决方案1】:

    尝试下面的 XPath 以通过跨度之一匹配元素:

    //li[.//span='diana' or .//span='mike']
    

    或两个跨度:

    //li[.//span='diana' and .//span='mike']
    

    【讨论】:

      【解决方案2】:

      要在一行中获取特定 li 标记内所有跨度的全文,您可以使用以下代码块:

      ArrayList<String> nameList = new ArrayList<String>();
      List<WebElement> firstName_lastname = driver.findElements(By.xpath("//li[@class='wdappchrome-ai']//span[@data-automation-id='searchInputAutoCompleteResultToken']"));
      for (WebElement fN_lN:firstName_lastname)
          nameList.add(fN_lN.getAttribute("innerHTML"));
      System.out.println(nameList);
      

      【讨论】:

      • 是否有机会仅使用 xpath 来实现它,因为我听说如果我们有大数据然后选择,列表 webelement 比 xpath 慢。同样在我的情况下,类名经常变化:(
      • 好吧,findElement 将始终返回一个 WebElement。但是由于您需要处理 2 个不同的WebElements,因此解决方案将基于多个xpaths(您的原始方式),或者您必须使用findElements。现在,我可以按需为您提供css,但这也不一定能保证更快的搜索。正如我所看到的,所涉及的class names 本身并不是动态的。如果是动态class names,我们可以很容易地适应制作xpath/css动态。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-11
      • 2021-09-22
      • 2022-08-17
      • 2010-10-07
      • 2014-02-07
      • 2018-10-30
      • 2021-04-05
      相关资源
      最近更新 更多