简体   繁体   中英

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

I want to find WebElement in a List<WebElements> by text. My method has such arguments: List<WebElement> webElements, String text . For matching text I prefer to use javaslang library. So, what we have:

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

}

Using javaslang I wrote such simple matching:

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. 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

Probably you need just a simple foreach loop:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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