Test if element is present using Selenium WebDriver?

We can verify if an element is present using Selenium. This can be determined with the help of findElements() method. It returns the list of elements matching the locator we passed as an argument to that method.

In case there is no matching element, an empty list [having size = 0] will be returned. We are not using the findElement() method since if there is no matching element, this method gives NoSuchElementException.

In an event of any exception, we have to handle it with a try catch block.


Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class ElementPresence{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/about/about_careers.htm";
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      List<WebElement> l=driver.findElements(By.xpath("//*[text()='Terms of Use']"));
      if(l.size()== 0){
         // empty list if no matching element
         System.out.println("Element not present, appearing "+l.size()+ " time");
      } else {
         System.out.println("Element present, appearing "+l.size()+ " time");


If the element is not present, the output is −

Updated on: 28-Aug-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started