如何通过文本在List <webelement>中查找WebElement?

时间:2017-03-21 13:56:13

标签: java loops selenium-webdriver pattern-matching vavr

我希望通过文字找到List<WebElement> webElements, String text中的WebElement。我的方法有这样的论点:protected WebElement findElementByText(List<WebElement> webelements, String text) { } 。对于匹配文本,我更喜欢使用javaslang库。那么,我们有什么:

Match(webElement.getText()).of(
     Case(text, webElement),
          Case($(), () -> {
               throw nw IllegalArgumentException(webElement.getText() + " does not match " + text);
          })
);

使用javaslang我写了这么简单的匹配:

List<WebElemnt>

我不明白如何以良好的方式编写循环以在{{1}}中通过文本查找WebElement。谢谢你们的帮助。

2 个答案:

答案 0 :(得分:2)

我建议这样做:

// using javaslang.collection.List
protected WebElement findElementByText(List<WebElement> webElements, String text) {
    return webElements
            .find(webElement -> Objects.equals(webElement.getText(), text))
            .getOrElseThrow(() -> new NoSuchElementException("No WebElement found containing " + text));
}

// using java.util.List
protected WebElement findElementByText(java.util.List<WebElement> webElements, String text) {
    return webElements
            .stream()
            .filter(webElement -> Objects.equals(webElement.getText(), text))
            .findFirst()
            .orElseThrow(() -> new NoSuchElementException("No WebElement found containing " + text));
}

免责声明:我是Javaslang的创建者

答案 1 :(得分:1)

可能你只需要一个简单的foreach循环:

for(WebElement element : webElements){
    //here is all your matching magic
}