匹配某个元素后停止搜索(XPath)

时间:2018-05-14 17:25:01

标签: xpath

我需要将元素与blockresult匹配,直到第一次出现具有类block但不是result的元素为止。

的XPath:

//div[contains(@class, 'result') and contains(@class ,'block')][following-sibling::div[contains(@class, 'block') and not(contains(@class,
'result'))]]

示例1(在这种情况下有效):

<div class="block result"></div> <!-- match this -->
<div class="block result"></div> <!-- match this -->
<div class="block"></div>
<div class="block result"></div> <!-- DONT match this -->
<div class="block result"></div> <!-- DONT match this -->

示例2(此处不匹配任何内容)

<div class="block result"></div> <!-- match this -->
<div class="block result"></div> <!-- match this -->

...所以它没有匹配第二个例子中的任何内容。我可以制作以下可选项,以便在两种情况下都匹配吗?

2 个答案:

答案 0 :(得分:1)

不漂亮,但应该有用......

//div[contains(concat(' ', @class, ' '), ' block ') and contains(concat(' ', @class, ' '), ' result ') and not(preceding-sibling::div[contains(concat(' ', @class, ' '), ' block ') and not(contains(concat(' ', @class, ' '), ' result '))])]

它应该将div与blockresult类匹配,但前提是它们不具有包含block类而不包含{{1}的前一个兄弟div }。class。

查看此问题的答案,了解我使用result的原因:

How can I match on an attribute that contains a certain string?

答案 1 :(得分:-1)

EDIT:

You can put in a List all which contain 'block' and after check with getAttribute("class") if contains "result" until not contain.

List<WebElement> aux = driver.findElements(By.xpath("//div[contains(@class ,'block')]"));

for(WebElement a : aux) {

    if(a.getAttribute("class").contains("result")) {

        System.out.println(a.getText()); //Save in other list


    }else {

        break;

    }

}