2016-07-14 194 views
3

我想选择以下仅顶部国家或只有其他国家如何过滤基于XPATH的元素?

<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 span元素,但在组合,他们没有工作。

我想只选择排名靠前的国家并将它们列入清单['Australia', 'Guinea-Bissau']并筛选出其他国家/地区。

如果我使用//*[text()='Top Countries']/../following-sibling::span所有国家都被选中。即。 ['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']

是动态生成的列表,以便基于文本/国名,我不能选择它们。

+0

请澄清一下,你在做什么?如果每个xpath单独工作,并且只想获得一个或另一个,那么只需使用单独的xpath。 –

+0

@BreaksSoftware增加了说明 – pr4bh4sh

回答

2

是:

//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

+0

感谢promt reply,''// span [text()='Top Countries'] /../ following-sibling :: span'''选择了我想要选择的所有元素[''澳大利亚','几内亚比绍'] – pr4bh4sh

+0

@ pr4bh4sh:我看到了,更新了查询。 – Jan

+1

谢谢@Jan。为什么我选择这个答案或选择以这种方式获取元素的解释很少。这个列表是非常有活力的,在这里的案例,无论是top还是其他都将出现,两者都将出现,两者都不存在。如果我不用Jan的定位器,我会最终嵌套如果其他和列表操作。这些定位器只有两个检查,根本没有任何列表操作。 – pr4bh4sh

0

这有帮助吗?假设总是有两个国家顶端国家

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

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

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现在将只包含“主要国家“