How do I find an element that contains specific text in Selenium Webdriver?


We can find an element with a specific text visible on the screen in Selenium. This is achieved with the xpath locator. The xpath locator contains some in-built functions that help to create customized xpath.

Let us consider a portion of the web page as given below −

  • text() − It is a built in function to identify an element based on the text displayed on the screen. For example, if we want to identify Library from the above webpage, the customized xpath with text() should be −

Syntax

//*[text()='Library']
  • contains() − It is a built in function to identify an element based on the partial text match. For example, if we want to identify GATE Exams from the above webpage, the customized xpath with contains() should be

Syntax

//*[contains(text(),'GATE')]

Example

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;
public class TextMatch{
   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(12, TimeUnit.SECONDS);
      // identify element with text()
      WebElement l=driver.findElement(By.xpath("//*[text()='Library']"));
      // identify element with contains()
      WebElement m=driver.findElement(By.xpath("//*[contains(text(),'GATE')]"));
      System.out.println("Element with text(): " + l.getText());
      System.out.println("Element with contains(): " + m.getText());
      driver.quit();
   }
}

Output

Updated on: 28-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements