How to Find Element by Text in Selenium: Tutorial

Jash Unadkat
2 min readNov 5, 2020

--

Locating the elements is the first step of running any automated test because test scripts must identify the element it has to interact with.

Refer to this detailed guide on Locators in Selenium to learn more about various locator strategies in Selenium.

In some cases, web developers tend to categorize web elements with identical class names or IDs. This can result in failed tests if the WebDriver cannot locate a certain web element.

In such cases, QA engineers can locate the element using text visible on-screen corresponding to that particular web element. This is possible using the Find Element by Text method using the Xpath locator.

We will consider an example depicting how to find an element by text in Selenium.

Prior to the example, let’s gather a fundamental understanding of the following two methods:

  1. text(): A built-in method in Selenium WebDriver that is used with XPath locator to locate an element based on its exact text value.
    Example: //*[ text() = ‘Get started free’ ]
  2. contains(): Similar to the text() method, contains() is another built-in method used to locate an element based on partial text match.
    For example, if we need to locate a button that has “Get started free” as its text, it can be located using the following line of code with Xpath.
    Example: //*[ contains (text(), ‘Get started’ ) ]

Let’s consider a simple scenario

  1. Launch the Chrome browser
  2. Navigate to BrowserStack’s website
  3. Locate the CTA with text value ‘Get started free’ using the XPath text() method.

A sample program for the above scenarios will be as follows:

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 Match{
public static void main(String[] args) {

System.setProperty("<Path of the ChromeDriver>");

WebDriver driver = new ChromeDriver();
String url = "https:/browserstack.com”;
driver.get(url);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Locating element with text()
WebElement e = driver.findElement(By.xpath("//*[text()='Get started free']"));

System.out.println("Element with text(): " + e.getText() );
driver.quit();
}
}

Similarly, one can locate the same CTA button by a partial text match using the contains() method.

Simply replace the text() method in the above program with the following code:

// located element with contains()
WebElement m = driver.findElement (By.xpath ("//*[contains(text(),'Get started ')]"));

The method above will locate the “Get started free” CTA based on the partial text match made against the string ‘Get started’.

--

--

Jash Unadkat
Jash Unadkat

Written by Jash Unadkat

As a tech geek, I love writing articles about everything related to web development or software testing space.

No responses yet