Selenium: check if element exists

29-10-2019 door Roy de Kleijn

Sometimes checking if an element exists on a page can be very useful. The code below demonstrates how to do that.

@Test
public void checkIfElementExists() {
	driver.get("http://www.github.com");

	if (driver.findElements(By.id("elementNotExists")).size() != 0) {
		System.out.println("Element exist");
	} else {
		System.out.println("Element doesn't exist");
	}
}

It returns a list of WebElements matching the locator and then it evaluates if the size is not equal to 0

Please be aware:

  1. If you use an implicitlyWait it can that longer if the element doesn't exists.
  2. The use of implicitlyWait is not the best. I highly recommend WebDriverWait.

Delen: