简体   繁体   English

Selenium XPath:祖先不包含

[英]Selenium XPath: ancestor does not contain

Find the div with class "bar" whose ancestor does not have class "foo" within the scope of top-level "foo".查找具有类“bar”的 div,其祖先在顶级“foo”范围内没有类“foo”。 For example,例如,

<div class="foo">
    <div class="foo">
         <div><div>
         <div class="bar"> </div>
         </div></div>
    </div>

    <div class="bar"> </div>
</div>

Find the bar not inside the nested "foo".找到不在嵌套“foo”内的栏。

And the XPath I tried is:我尝试的 XPath 是:

WebElement root = driver.findElement(By.xpath("//div[@class='foo']"));
root.findElements(By.xpath(".//div[not(contains(@class, 'foo'))]//div[contains(@class, 'bar')]"));

But the XPath returns two elements.但是 XPath 返回两个元素。 Also tried css selector:还试过 css 选择器:

root.findElements(By.cssSelector(":not(.foo) .bar"));

Not working either.也不工作。

Try this XPath-1.0 expression:试试这个 XPath-1.0 表达式:

//div[contains(@class, 'bar') and not(ancestor::*[@class='foo'])]

It only returns one item: the desired <div class="bar"> </div> .它只返回一项:所需的<div class="bar"> </div>

这个只返回第二个栏(至少当我运行它时......)

//*[@class='bar'][(parent::div[@class='foo'])]

如果您尝试使用 bar 类访问直接子 div,那么这里是 xpath。

//div[@class='bar' and parent::div[@class='foo']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM