XPath Selenium:根据对等节点的存在选择节点

时间:2014-08-20 03:32:30

标签: selenium xpath selenium-webdriver webdriver

民间,

我试图了解如何使用对等节点的组合

我的问题的第1部分

我需要帮助将xpath表达式放在一起,以便仅使用链接填充集合,这些链接具有作为对等节点(存在)的范围。

a)添加到集合

<div style="font-weight:bold;padding-top:4px;padding-left:10px;text-align:left;white-space:nowrap;">
    <a class="LeftNavLink" href="find/all-years/alfa-romeo" style="margin-left:14px;">Alfa Romeo</a><span style="font-weight:normal;"> (121)</span>
</div>

b)不要添加到集合

<div style="font-weight: bold; padding-top: 4px; padding-left: 10px;">
    <a href="find?tags=convertible" class="LeftNavLink">Convertibles</a>
</div>

我的问题的第2部分

什么是xpath表达式,以便仅使用链接填充集合,链接具有作为具有特定属性的对等节点的范围(例如,style =&#34; font-weight&#34; not style =&#34 ;字型重量:正常;&#34)

提前谢谢。

2 个答案:

答案 0 :(得分:1)

对于你的第一个问题,这是相当简单的,但鉴于你的HTML,应该工作:

//div/span/../a

这会找到<div>,其中<span>作为孩子,返回父母(<div>),然后找<a>

关于你的第二个问题:

//div/span[contains(@style, 'font-weight:') and not(contains(@style,'font-weight:normal;'))]/../a

这里的区别在于<span>,使用contains()查找style="font-weight:",然后使用and not(contains())来排除style="font-weight:normal;" < / p>

对于您的上一个问题,您不会从<a>及其同行<span?获取文字。我建议使用har07的方法:

//div[a and span]/span

使用它来获取另一个List

List<WebElement> span1 = driver.findElements(By.xpath ("//div[a and span]/span"));

答案 1 :(得分:0)

基本上,您可以选择<div><span><a>个孩子,然后以这种方式获取<a>孩子:

//div[a and span]/a

您可能希望根据需要添加一些过滤器([....])以使其更具体。第二个要求可以使用类似的XPath,但为<span>元素使用更具体的过滤器,例如:

//div[a and span[
                  contains(@style, 'font-weight') 
                    and 
                  not(contains(@style, 'font-weight:normal'))
                 ]]/a