Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Selenium 如何基于XPATH过滤元素?_Selenium_Xpath - Fatal编程技术网

Selenium 如何基于XPATH过滤元素?

Selenium 如何基于XPATH过滤元素?,selenium,xpath,Selenium,Xpath,我想选择仅在顶级国家或其他国家/地区之后的跨度元素 <div> <div> <span class="hb">Top Countries</span> </div> <span>Australia</span> <span>Guinea-Bissau</span> <div> <span class="hb">Other</

我想选择仅在顶级国家或其他国家/地区之后的跨度元素

<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而不是(//*[text()='Other']/../following sibling::span)

如果我分别尝试这两种XPATH,它们都可以工作,但如果组合使用,它们就不能工作

我只想选择排名靠前的国家,并将它们列在一个列表中
['Australia'、'几内亚-比绍']
,然后过滤掉其他国家

如果我使用
/*[text()='Top Countries']/../following sibling::span
将选择所有国家。例如,
[“澳大利亚”、“几内亚比绍”、“西班牙”、“瑞士”、“英国”、“美国”、“奥地利”、“毛里塔尼亚”、“毛里求斯”、“瑙鲁”、“帕劳”、“沙特阿拉伯”]

使用
/*[text()=“Other”]/../span选择的下列兄弟姐妹::span
项目是
[“奥地利”、“毛里塔尼亚”、“毛里求斯”、“瑙鲁”、“帕劳”、“沙特阿拉伯”]

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

它是:

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

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


看看精彩之处。

这有帮助吗?假设在顶级国家下总是有两个国家

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

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

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"));

所有
现在只包含“顶级国家”

请澄清,您想做什么?如果每个xpath单独工作,并且您只想获取其中一个xpath,那么只需使用单独的xpath即可。@BreaksSoftware为promt reply添加了澄清库,
///span[text()=“Top Countries”]/../following sibling::span
选择我只想选择的所有元素['Australia'、'几内亚比绍']谢谢@Jan。我没有什么解释为什么选择这个答案或者选择以这种方式获取元素。这个列表是非常动态的,这里的案例,要么是top,要么是other,两者都会出现,都不会出现。如果我不使用Jan的定位器,我将以嵌套的If-else和列表操作结束。使用这些定位器,只需进行两次检查,根本不需要进行列表操作。@pr4bh4sh:Gald to help:)
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"));
all.removeAll(other);