0 votes
1 view
in Devops and Agile by (19.8k 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 the test, so an exception can not be the solution.

I've found this post: Selenium c# Webdriver: Wait Until Element is Present But this is for C# and I am not very good at it. Can anyone translate the code into Java? I am sorry guys, 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 (63.4k points)

In order to check if an element is present on a webpage, we make use of the driver.findElements() method. As we know that driver.findElements() method returns a list of web elements located by the "By Locator" passed as parameter. If an element is found then it returns a list of non-zero web elements else it returns a size 0 list. Thus, checking the size of the list can be used to check for the presence and absence of elements.

List<WebElement> dynamicElement = driver.findElements(By.id("id"));

if(dynamicElement.size() != 0){

//If list size is non-zero, element is present

System.out.println("Element present");



//Else if size is 0, then element is not present

System.out.println("Element not present");


Welcome to Intellipaat Community. Get your technical queries answered by top developers !