WebDriver: check if an element exists?

Ralph picture Ralph · Jun 29, 2011 · Viewed 378.9k times · Source

How to check if an element exist with web driver?

Is using a try catch really the only possible way?

boolean present;
try {
   driver.findElement(By.id("logoutLink"));
   present = true;
} catch (NoSuchElementException e) {
   present = false;
}

Answer

Mike Kwan picture Mike Kwan · Jun 29, 2011

You could alternatively do:

driver.findElements( By.id("...") ).size() != 0

Which saves the nasty try/catch