How do I determine if a WebElement exists with Selenium?

dsidler picture dsidler · Dec 13, 2016 · Viewed 10.1k times · Source

I know I could use (driver.findElements(By.xpath("Xpath Value")).size() != 0);

However, I am using a Page Object Model, who's entire purpose is to predefine the WebElements in a separate class, so I don't have to "FindElements By" in my test classes.

Here's what I currently have

if (objPage.webElement.isEnabled()){
   System.out.println("found element");
}else{
   System.out.println("element not found");
}

However, this tries to identify the possibly non-existent WebElement. When it is not present, I get:

No Such Element" exception.

Answer

JeffC picture JeffC · Dec 14, 2016

Best practice is to do what you originally suggested, use .findElements() and check for .size != 0 or you can also use my preference, .isEmpty(). You can create a Util function like the below to test if an element exists.

public boolean elementExists(By locator)
{
    return !driver.findElements(locator).isEmpty();
}

You could also build this into a function in your page object.