user5880424 user5880424 - 2 months ago 29
Java Question

How can I loop through list of WebElements and select one WebElement with a condition?

I am using Selenium WebDriver with Java. I am trying to create a method that loops through a list of WebElements to return the first WebElement that contains the text "Ooga Booga", or return null if there are no elements in the list that contains this text.

public class myClass {
private static WebElement element = null;
private static List<WebElement> elements = null;

public static WebElement returnOneElement (WebDriver driver){
elements = driver.findElements(By.cssSelector("someSelector"));
for (WebElement element : elements){
String myText = element.findElement(By.cssSelector("someDiv")).getText();
if (myText.contains("Ooga Booga")) {
return element;
}
}
return null;
}


This all works fine until I run into an element that does not have this attribute:

String myText = element.findElement(By.cssSelector("someDiv")).getText();


How can I continue to loop through my List while ignoring any elements that do not have "someDiv" inside of it?

Answer

Use findElement-S method as shown below.

    for (WebElement element : elements) {
        List<WebElement> mightHaveSomeDiv = element.findElements(By.cssSelector("someDiv"));

        if (mightHaveSomeDiv.size() > 0) {
            //Can iterate the list if you expect more than one div of type someDiv.
            String myText = mightHaveSomeDiv.get(0).getText();
            if (myText.contains("Ooga Booga")) {
                return element;
            }
        }
    }