How can I check if some text exist or not in the page using Selenium?


We can check if some text exists or not in a page with Selenium. There are more than one ways to find it. We can use the getPageSource() method to fetch the full page source and then verify if the text exists there. This method returns content in the form of string.

We can also check if some text exists with the help of findElements method with xpath locator. Then we shall use the text() function to create a customized xpath. The findElements() method returns a list of elements. We shall use the size() method to verify if list size is greater than 0.

Suppose we want to verify if the below text exists in 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 TextExistFindElemnts{
   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/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      String t = "You are browsing the best resource for Online Education";
      // identify elements with text()
      List<WebElement> l= driver.findElements(By.xpath("//*[contains(text(),'You are browsin')]"));
      // verify list size
      if ( l.size() > 0){
         System.out.println("Text: " + t + " is present. ");
      } else {
         System.out.println("Text: " + t + " is not present. ");
      }
   }
}

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 TextExistPgSource{
   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/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      String t = "You are browsing the best resource for Online Education";
      // getPageSource() to get page source
      if ( driver.getPageSource().contains("You are browsin")){
         System.out.println("Text: " + t + " is present. ");
      } else {
         System.out.println("Text: " + t + " is not present. ");
      }
   }
}

Output

Updated on: 28-Aug-2020

16K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements