Hero Background

Power Your Software Testing with AI Agents and Cloud

The Native AI-Agentic Cloud Platform to Supercharge Quality Engineering. Test Intelligently and Ship Faster.

Selenium JavaAutomationTutorial

How to Find Element by Text in Selenium

Learn how to findElement() by text in Selenium for dynamic IDs and Classes. Overcome challenges, enhance automation testing, and gain practical insights.

Last Updated on:

Locating WebElements precisely is essential for reliable Selenium testing. One commonly used technique is to find elements by text in Selenium, which helps identify elements based on their visible text, especially when other attributes aren’t unique or consistent.

TL;DR

  • Find element by text in Selenium locates a WebElement by its visible text when IDs and class names are dynamic.
  • XPath is the locator strategy, with text() for an exact match and contains() for a partial one.
  • text() matches the whole string, so it suits labels that are static and predictable.
  • contains() matches only part of the string, which handles text that changes between runs.
  • findElements() returns every match, so reach for it when more than one element shares the same text.
  • Running the same suite on a cloud Selenium grid covers browser and OS combinations without maintaining a local grid.

What Is Find Element by Text in Selenium?

Find element by text in Selenium is a way to locate a WebElement based on its visible text content using the findElement() method. It is useful when attributes like ID or ClassName are dynamic or unreliable for identification.

XPath is typically used as the locator strategy, leveraging the text() method to find element by text in Selenium.

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

Methods to Find Element by Text in Selenium

To find element by text in Selenium, you can use the text() and contains() methods in your XPath with the findElement() method.

  • text(): This built-in method in Selenium is used with XPath to locate an element based on its exact text value:
  • WebElement ele = driver.findElement(By.xpath("//*[text()='textvalue']"))
    

You can also extract text from a web page and print it in the console using the getText() method.

  • contains(): It is another built-in method which is used with XPath. However, this is used when writing the locator based on a partial text match.
  • WebElement ele =driver.findElement(By.xpath("//*[contains(text(),'textvalue')]"))
    

Using findElement() Method for Complete Text Match

To find element by text in Selenium for complete text match, you can use the findElement() method. Here’s an example:

Test Scenario:

  • Log in to the TestMu AI Selenium Playground.
  • Identify the WebElement for the Checkbox Demo link using the text() method.
  • Click on it and print the page header.

Typically, you might run Selenium scripts on a local grid setup. However, here we’ll execute the test script on an online Selenium Grid using TestMu AI. This allows us to run tests in parallel across various browser and OS combinations without managing any infrastructure.

To get started, check out this documentation on Selenium testing with TestMu AI.

Note

Note: Run Selenium tests across 3,000+ browser and OS combinations. Try TestMu AI Now!

Step 1: Inspect the Element

  • Open the web page and right-click on the Checkbox Demo link.
  • Click Inspect to open the browser developer tools. In the Elements tab, you’ll see the HTML structure of the web page.
  • Use the anchor tag (a) and the text “Checkbox Demo” to find this element using XPath.
  • WebElement checkbox = driver.findElement(By.xpath("//a[text()='Checkbox Demo']"));
    
  • Open Eclipse IDE and create a Maven project named FindElementByText.
  • Inside the src folder, add a new package named test to hold all test files.
  • Create a BaseTest.java file to handle WebDriver setup, teardown, and TestMu AI cloud grid connection.
  • Update your pom.xml file with Selenium and TestNG dependencies.
  • <project xmlns="http://maven.apache.org/POM/4.0.0"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
       <modelVersion>4.0.0</modelVersion>
       <groupId>FindElementByText</groupId>
       <artifactId>FindElementByText</artifactId>
       <version>0.0.1-SNAPSHOT</version>
       <build>
           <sourceDirectory>src</sourceDirectory>
           <plugins>
               <plugin>
                   <artifactId>maven-compiler-plugin</artifactId>
                   <version>3.8.1</version>
                   <configuration>
                       <release>17</release>
                   </configuration>
               </plugin>
           </plugins>
       </build>
       <dependencies>
           <dependency>
               <groupId>org.seleniumhq.selenium</groupId>
               <artifactId>selenium-java</artifactId>
               <version>4.16.1</version>
           </dependency>
           <dependency>
               <groupId>org.testng</groupId>
               <artifactId>testng</artifactId>
               <version>7.8.0</version>
               <scope>test</scope>
           </dependency>
       </dependencies>
    </project>
    
  • Create BaseTest.java file to set up and tear down the WebDriver, with connectivity to TestMu AI Selenium Grid.
  • public class BaseTest {
      
         public RemoteWebDriver driver = null;
    
    
         String username = System.getenv("LT_USERNAME") == null ? "<lambdatest_username>" : System.getenv("LT_USERNAME");
         String accessKey = System.getenv("LT_ACCESS_KEY") == null ? "<accesskey>" : System.getenv("LT_ACCESS_KEY");
    
    
         @BeforeTest
         public void setup()
         {
             try
             {
                 ChromeOptions chromeOptions = new ChromeOptions();
                 chromeOptions.setPlatformName("Windows 10");
                 chromeOptions.setBrowserVersion("121.0");
                            
                 HashMap<String, Object> ltOptions = new HashMap<String, Object>();
    ltOptions.put("build", "Find Element by Text");
        		  ltOptions.put("project", "Find Element by Text in Selenium");
                 chromeOptions.setCapability("LT:Options", ltOptions);
    
    
                 driver = new RemoteWebDriver(
                         new URL("https://" + username + ":" + accessKey + "@hub.lambdatest.com/wd/hub"), chromeOptions);
             }
             catch (MalformedURLException e)
             {
                 e.printStackTrace();
             }
         }
    
    
         @AfterTest
         public void tearDown()
         {
             driver.quit();
         }
    }
    

You can get your TestMu AI Username and Access Key from your Account Settings > Password & Security to connect to the cloud grid for test execution. Alternatively, you can configure these as environment variables and directly fetch them in the test script.

After that, create a HashMap type variable to pass the additional browser capabilities required by the TestMu AI platform to support test execution on their cloud grid.

You can fetch the required browser capabilities for the TestMu AI platform by navigating to the Automation Capabilities Generator.

  • Create TestFindByTextForCompleteMatch.java file to perform the actual text match operation.
  • public class TestFindByTextForCompleteMatch extends BaseTest{
    
    
       @Test
       public void testFindElementByCompleteTextMatch()
       {
           System.out.println("Logging into TestMu AI Selenium Playground");
           driver.get("https://www.testmuai.com/selenium-playground/");
           WebElement checkBoxDemoPage= driver.findElement(By.xpath("//a[text()='Checkbox Demo']"));
           checkBoxDemoPage.click();
           System.out.println("Clicked on the Checkbox Demo Page");
           WebElement header=driver.findElement(By.xpath("//h1"));
           System.out.println("The header of the page is:"+header.getText());
       }
    }
    

Using findElement() Method for Partial Text Match

  • Log in to the TestMu AI Selenium Playground.
  • Identify all the WebElements that have “Table” in their names.
  • Print the text of all such WebElements.
  • Right-click on any WebElement with “Table” in its name and select Inspect to open the browser developer tools.
  • In the Elements tab, use the anchor tag and partial text “Table” with XPath contains() method to locate these elements.

If there is more than one WebElement, you can use the findElements() method.

The findElements() method returns the list of WebElements that match the locator value, unlike the findElement() method, which returns only a single WebElement.

If there are no matching elements within the web page, the findElements() method returns an empty list.

    List tableOptions=driver.findElements(By.xpath("//a[contains(text(),'Table')]")
    
public class TestFindByTextForPartialMatch extends BaseTest {


   @Test
   public void testFindElementByPartialTextMatch() {


       System.out.println("Logging into TestMu AI Selenium Playground");
       driver.get("https://www.testmuai.com/selenium-playground/");
       List tableOptions = driver.findElements(By.xpath("//a[contains(text(),'Table')]"));
       for (WebElement e : tableOptions) {
           System.out.println("The different options with table in name are:" + e.getText());
       }
   }
}

Using findElement() Method With text() and contains() Methods

  • Log in to the TestMu AI Selenium Playground.
  • Identify WebElements that have “Dynamic” in its name and click on it.
  • Print the header of the loaded page after the action.
WebElement element= driver.findElement(By.xpath("//a[contains(text(),'Dynamic')]")
public class TestFindByTextForSpecificContainingText extends BaseTest {
   @Test
   public void testFindElementBySpecificTextMatch() {
       System.out.println("Logging into TestMu AI Selenium Playground");
       driver.get("https://www.testmuai.com/selenium-playground/");
       WebElement element = driver.findElement(By.xpath("//a[contains(text(),'Dynamic')]"));
       element.click();
       System.out.println("Clicked on the Dynamic Data Loading link");
       WebElement header = driver.findElement(By.xpath("//h1"));
       System.out.println("The header of the page is:" + header.getText());
   }


}

Conclusion

Finding an element by its visible text is the locator strategy that survives a redesign. When IDs and class names are generated at build time, the label a user actually reads is often the only stable handle on the element, and XPath's text() and contains() give you both the exact and the partial match.

Reach for text() when the label is fixed and contains() when only part of it is, and prefer a narrower path such as //a[text()='Submit'] over //* so the query stays readable and fast. Once the locators hold, run the suite across browsers on a cloud Selenium grid, using the capabilities and documentation linked earlier in this guide.

Author

...

Vipul Gupta

Blogs: 24

  • Twitter
  • Linkedin

Vipul Gupta is a Sr. Lead SDET at Zupee with over 9 years of experience in functional and automation testing. He has built 10+ automation projects from scratch covering web, API, and mobile applications. Vipul is skilled in Selenium, Appium, Rest Assured, Playwright, Java, Python, Pytest, BDD, TDD, Maven, Jenkins, TestNG, and JUnit. He has successfully led end-to-end QA efforts, including setting up teams from scratch and managing a 15-member QA team to ensure manual and automation testing run in parallel from day one. Vipul graduated in B.Tech CSE from CGC College of Engineering and is followed by 3,000+ QA and SDET professionals on LinkedIn, reflecting his strong influence in the testing community.

Reviewer

...

Himanshu Sheth

Reviewer

  • Linkedin

Himanshu Sheth is the Director of Marketing (Technical Content) at TestMu AI, with over 8 years of hands-on experience in Selenium, Cypress, and other test automation frameworks. He has authored more than 130 technical blogs for TestMu AI, covering software testing, automation strategy, and CI/CD. At TestMu AI, he leads the technical content efforts across blogs, YouTube, and social media, while closely collaborating with contributors to enhance content quality and product feedback loops. He has done his graduation with a B.E. in Computer Engineering from Mumbai University. Before TestMu AI, Himanshu led engineering teams in embedded software domains at companies like Samsung Research, Motorola, and NXP Semiconductors. He is a core member of DZone and has been a speaker at several unconferences focused on technical writing and software quality.

Add to Google preferred sources

Summarise with AI

Copied to Clipboard!
...

3000+ Browsers. One Platform.

See exactly how your site performs everywhere.

Try it free
...

Write Tests in Plain English with KaneAI

Create, debug, and evolve tests using natural language.

Try for free

Find Element by Text in Selenium FAQs

Did you find this page helpful?

More Related Blogs

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests