How do I verify that an element does not exist in Selenium 2?


We can verify if an element does not exist in Selenium webdriver. To achieve this, we shall use the method getPageSource which gets the entire page source. So we can obtain a complete page source and check if the text of the element exists.

We also use the findElements method and utilize any locators like xpath, CSS, and so on to identify the matching elements. The findElements gives an elements list.

We shall count the number of elements returned by the list with the help of the size method. If the value of size is greater than 0, then the element exists and if it is lesser than 0, then the element does not exist.

Let us verify if the highlighted text is present on the page −

Example

Code Implementation with findElements().

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 ExistElements{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/index.htm");
      String str = "You are browsing the best resource for Online Education";
      // identify elements
      List<WebElement> m= driver.findElements(By.xpath("//*[contains(text(),'You are browsin')]"));
      // verify size
      if ( m.size() > 0){
         System.out.println("Text: " + str + " is present. ");
      }
      else{
         System.out.println("Text: " + str+ " is not present. ");
      }
      driver.quit();
   }
}

Example

Code Implementation with getPageSource.

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;
public class ElementExistPgSource{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/index.htm");
      String str = "You are browsing the best resource for Online Education";
      //get page source
      if ( driver.getPageSource().contains("You are browsin")){
         System.out.println("Text: " + str + " is present. ");
      }
      else{
         System.out.println("Text: " + str + " is not present. ");
      }
      driver.quit();
   }
}

Output

Updated on: 01-Feb-2021

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements