【问题标题】:How to filter elements based on XPATH?如何根据 XPATH 过滤元素?
【发布时间】:2016-07-15 02:38:43
【问题描述】:

我想选择只跟随顶级国家或只跟随其他国家的 span 元素

<div>
  <div>
    <span class="hb">Top Countries</span>
  </div>
  <span>Australia</span>
  <span>Guinea-Bissau</span>
  <div>
    <span class="hb">Other</span>
  </div>
  <span>Austria</span>
  <span>Mauritania</span>
  <span>Mauritius</span>
  <span>Nauru</span>
  <span>Palau</span>
  <span>Saudi Arabia</span>
</div>

我试过//*[text()='Top Countries']/../following-sibling::span and not(//*[text()='Other']/../following-sibling::span)

如果我分别尝试这两个 XPATH,它们会起作用,但结合起来,它们就不起作用。

我只想选择排名靠前的国家并将它们列入列表['Australia', 'Guinea-Bissau'] 并过滤掉其他国家。

如果我使用//*[text()='Top Countries']/../following-sibling::span所有国家/地区都会被选中。 IE。 ['Australia', 'Guinea-Bissau', 'Spain', 'Switzerland', 'UK', 'USA', 'Austria','Mauritania', 'Mauritius','Nauru','Palau','Saudi Arabia']

选择//*[text()='Other']/../following-sibling::span 的项目是['Austria','Mauritania', 'Mauritius','Nauru','Palau','Saudi Arabia']

该列表是动态生成的,因此我无法根据文本/国家/地区名称选择它们。

【问题讨论】:

  • 请澄清,你想做什么?如果每个 xpath 单独工作,而您只想获取其中一个,则只需使用单独的 xpath。
  • @BreaksSoftware 添加了说明

标签: selenium xpath


【解决方案1】:

它是:

//span[preceding-sibling::div[1]/descendant::text()='Top Countries']

这个选择:

Element='<span>Australia</span>'
Element='<span>Guinea-Bissau</span>'


显然,只选择其他国家
//span[preceding-sibling::div[1]/descendant::text()='Other']


看到精彩的online xpath tester

【讨论】:

  • 感谢您的及时回复,//span[text() = 'Top Countries']/../following-sibling::span 选择了我只想选择的所有元素 ['Australia', 'Guinea-Bissau']
  • 谢谢@Jan。很少解释为什么我选择这个答案或选择以这种方式获取元素。列表非常动态,这里的案例,要么 top 要么 other 都会出现,两者都会出现,都不会有。如果我不使用 Jan 的定位器,我最终会使用嵌套的 if else 和列表操作。使用这些定位器,只需进行两次检查,根本不需要列表操作。
  • @pr4bh4sh: Gald 来帮忙 :)
【解决方案2】:

这有帮助吗?假设 Top countries 下总是有 两个国家

//span[text() = 'Top Countries']/../following-sibling::span[1]
//span[text() = 'Top Countries']/../following-sibling::span[2]

【讨论】:

    【解决方案3】:

    您可以创建两个列表,一个包含所有元素,一个包含不需要的元素

    List<WebElement> all = driver.findElements(By.xpath("//*[text()='Top Countries']/../following-sibling::span"));
    List<WebElement> other = driver.findElements(By.xpath("//*[text()='Other']/../following-sibling::span"));
    

    然后删除 other 国家/地区

    all.removeAll(other);
    

    all 现在将只包含“热门国家/地区”

    【讨论】:

      猜你喜欢
      • 2017-07-22
      • 2010-10-03
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      • 1970-01-01
      相关资源
      最近更新 更多