How to identify elements based on text visible on page in Selenium?



To identify elements based on text visible on page, text() method is used in xpath.

Syntax

driver.findElement(By.xpath("//tagname[text()=’value’]"))

Example

import org.openqa.selenium.By; import org.openqa.selenium.Keys; 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().window().maximize();       driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);       //xpath with text() method       driver.findElement(By.xpath("//*[text()=’GATE Exams’]")).click();       driver.close();    } }
Updated on: 2020-06-10T12:59:04+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements