javaseleniumselenium-webdriverpageobjects

How do I determine if a WebElement exists with Selenium?


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

However, I am using a Page Object Model, whose 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.


Solution

  • 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 utility 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.