Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.7k points)

Is there a way how to test if an element is present? Any findElement method would end in an exception, but that is not what I want, because it can be that an element is not present and that is okay, that does not fail of the test, so an exception can not be the solution.

I tried it out in Eclipse but I don't get it right into Java code.

This is the code:

public static class WebDriverExtensions{

    public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds){

        if (timeoutInSeconds > 0){

            var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));

            return wait.Until(drv => drv.FindElement(by));

        }

        return driver.FindElement(by);

    }

}

1 Answer

0 votes
by (62.9k points)

Use findElements instead of findElement.

findElements will return an empty list if no matching elements are found instead of an exception.

To check that an element is present, you could try this

Boolean isPresent = driver.findElements(By.yourLocator).size() > 0

This will return true if at least one element is found and false if it does not exist.

For more related queries, please check our blog on Selenium interview questions. Or, also you can go for Selenium certification online.

Browse Categories

...