简体   繁体   English

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

[英]How to find WebElement in a List<WebElement> by text?

I want to find WebElement in a List<WebElements> by text. 我想通过文本在List<WebElements>找到WebElement。 My method has such arguments: List<WebElement> webElements, String text . 我的方法有这样的参数: List<WebElement> webElements, String text For matching text I prefer to use javaslang library. 对于匹配的文本,我更喜欢使用javaslang库。 So, what we have: 那么,我们有什么:

protected WebElement findElementByText(List<WebElement> webelements, String text) {

}

Using javaslang I wrote such simple matching: 使用javaslang我写了这么简单的匹配:

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

I do not understand how in good way to write a loop for finding WebElement in a List<WebElemnt> by text. 我不明白如何以良好的方式编写一个循环来通过文本在List<WebElemnt>查找WebElement。 Thank you guys for help. 谢谢你们的帮助。

I suggest to do it like this: 我建议像这样做:

// 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));
}

Disclaimer: I'm the creator of Javaslang 免责声明:我是Javaslang的创造者

Probably you need just a simple foreach loop: 可能你只需要一个简单的foreach循环:

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

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

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