1

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.

Denis Koreyba
  • 3,144
  • 1
  • 31
  • 49
Oleksii
  • 1,623
  • 20
  • 26

2 Answers2

3

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

Daniel Dietrich
  • 2,262
  • 20
  • 25
1

Probably you need just a simple foreach loop:

for(WebElement element : webElements){
    //here is all your matching magic
}
Denis Koreyba
  • 3,144
  • 1
  • 31
  • 49
  • Let's imagine that List has size three and needed element is second. That loop will run just once. java.lang.IllegalArgumentException: Something does not match ExpectedText message will apear at console. – Oleksii Mar 21 '17 at 15:08
  • as I figured out my first fault was adding IllegalArgumentException. For that reason loop was run just once. – Oleksii Mar 21 '17 at 15:46
  • I have resolved my issue in half. It works with foreach and if else. But maybe somebody could help me to do it using pattern matching. – Oleksii Mar 21 '17 at 15:49
  • @Oleksii don't make the life harder.) Why do you throw exception if you can't handle it? Instead of it return true/false. Then check the answer and if it's true then return your element. – Denis Koreyba Mar 21 '17 at 16:05