Selenium Find Element By Text

Profile picture for user arilio666

In Selenium using Java, you can find an element by its text using the XPath method. 
Here is an example of how to find an element with the text "Text" using XPath:

WebElement element = driver.findElement(By.xpath("//*[text()='Text']"));

We can also prefer the contains method using XPath to fetch elements based on text.

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

Let us try to fetch the ask doubt text of our programsbuzz site.

        ChromeDriver driver = new ChromeDriver();
        driver.findElement(By.xpath("(//a[text()='Ask Doubt'])[2]")).click();
  •  have provided it with the index as it was present on the second index.
  • After some animation wait time, it will click on the ask doubt button on the second index.
(//*[ contains (text(), 'Ask Doubt' ) ])[2]
  • The same thing can also be done using contains too.