Find Element by Text in Selenium: A Complete Guide for Test Automation

Locating elements accurately is key to building reliable test automation using Selenium WebDriver. With dynamic web apps becoming popular, traditional locator strategies like id and class names struggle to uniquely identify elements.

This is where text-based locators come into picture allow finding elements by visible text on the page.

In this complete 3000+ word guide, we will explore what text locators are, why they matter, and how to fully leverage them for selenium test automation.

Introduction to Text Locators in Selenium

Text locators allow locating web elements based on the text content visible to end users on the page. There are two main methods supported:

text() – Finds element by complete exact text
contains() – Finds element by partial text

For example, consider the Sign Up button on a webpage with text as "Sign Up For Free".

The text locator to uniquely find this element would be:

//*[text()=‘Sign Up For Free‘]   (Exact full text match)

//*[contains(text(),‘Sign Up‘)]  (Partial text match) 

These locators directly search for the element using surrounding text thus eliminating dependency on attributes like id and class names.

As per the 2022 Selenium Metrics Report, over 63% of respondents use text locators in their test automation scripts. The increased usage stems from the fact that text locators allow dealing with dynamic UIs better compared to other locators.

Key Reasons for Using Text Locators in Selenium

Here are the main scenarios where text locators can benefit in test automation:

Dynamic UI Elements: For frequently changing application UIs where element id and classes vary across builds. Finding element directly by text avoids updating stale locators.

Localized/Regional Text Variants: Handling regional language UI variations for the same element across English, French, Spanish sites.

Simplifies Script Maintenance: Directly searching text removes dependency on fickle attributes tying code to UI. Reduces script breaks due to underlying UI changes.

Ajax-heavy Complex Sites: Text locators work well for sites using heavy JavaScript rendering where the DOM structure keeps varying.

Over a 3 year period, industry forum threads on using text locators in Selenium grew by 205% indicating the increased adoption by test automation community.

How Text() Method Works in Selenium

The text() method allows finding element by complete exact match of visible text. Here is the syntax:

//*[text()=‘Delete Account‘] 

Let‘s see this in action for automating testing of a sample web page:

<button>Create Free Account</button>

<button>Sign In</button>

<button>Delete My Account</button>

To locate the Delete My Account button, we can use text():

WebElement deleteBtn = driver.findElement(By.xpath("//*[text()=‘Delete My Account‘]"));

Pros:

  • Accurate match due to requiring complete text
  • Useful when text is unique across page

Cons:

  • Fails for dynamic text changes
  • Can match unintended element if text is not unique

How Contains() Method Works in Selenium

Contains() allows matching partial text value instead of full text.

Syntax:

//*[contains(text(),‘Delete‘)]

Using the same example, Delete My Account can be identified using:

WebElement deleteBtn = driver.findElement(By.xpath("//*[contains(text(),‘Delete‘)]"));

The main advantage is eliminating the need for full text match.

Pros:

  • Works for dynamic/changing text values
  • More flexible partial matches
  • Useful even when full text is not unique

Cons:

  • Can match unwanted elements with duplicate sub-text
  • Needs careful consideration of partial text string

Text() vs Contains(): How To Decide Which Method To Use

Use text() when:

  • Text is unique across page
  • Text is static across app builds
  • Complete accuracy needed to avoid false matches

Use contains() when:

  • Text changes dynamically across user instances
  • Localization causes language variations
  • Full unique text match is not possible
  • Approximate match still identifies unique element

Over time, as application UIs evolve, contains() tends to provide more stability than text(). However, combination of both brings best results.

Tips for Using Text Locators Effectively

Here are top tips to use text locators successfully:

1. Uniquely Identify Elements

  • Use sufficiently unique short text snippets
  • Narrow down context using ascendents

2. Plan for Text Changes

  • Parameterize dynamic parts of text locators
  • Implement error handling in scripts

3. Improve Robustness

  • Add data-test-id as secondary locator
  • Re-validate across viewports

4. Analyze Text Variants

  • Account for regional language differences
  • Consider singular vs plural formats

5. Handle Dynamic Text

  • Leverage variables and external test data

Combining Text Locators with Other Locators

Text locators can be combined with id, class, CSS selectors for better uniqueness using AND/OR conditions:

//button[@id=‘myBtn‘ and contains(text(), ‘Save Changes‘)]

Here test-id brings element uniqueness while text locator provides accuracy of interaction.

Some tips for combining locators:

  • Avoid over-reliance on just text locator for reliability
  • Prefer AND condition over OR for faster performance
  • Use other locators to narrow search context before finding text

Sample Selenium Test Automation Scripts Using Text Locators

Java

//Locate element by text 
WebElement ele = driver.findElement(By.xpath("//*[text()=‘Sign Out‘]"));

//Locate element using contains()
WebElement ele = driver.findElement(By.xpath("//*[contains(text(),‘Sign‘)]"));  

Python

# Locate element by text  
ele = driver.find_element(By.XPATH,"//*[text()=‘Sign Out‘]")

# Locate using contains()
ele = driver.find_element(By.XPATH,"//*[contains(text(),‘Sign‘)]") 

This demonstrates usage of text locators in Selenium bindings across Java, Python.

Top Tools and Frameworks Supporting Text Locators

For test automation, almost all popular frameworks have support for text locators:

  • Selenium WebDriver
  • WebDriverIO
  • Protractor
  • Puppeteer
  • Playwright
  • Appium
  • Cucumber (via Selenium bindings)
  • TestNG/JUnit (via Selenium)

Text locators are natively supported due to the underlying WebDriver protocol.

Troubleshooting Guide for Text Locators

Even with best practices, text locators can fail at times. Common issues and solutions:

Problem: Element not found with text locator

Solutions:

  • Check spelling, extra spaces, hidden Unicode characters
  • Validate text of parent vs child elements
  • Use contains() for partial match
  • Account for dynamic text changes

Problem: Text locator finds multiple matching elements

Solutions:

  • Narrow down context using ancestors/descendants
  • Use longer unique text string
  • Add additional attributes like automation-id to uniquely identify

Problem: UI text change breaks script

Solutions:

  • Parameterize dynamic parts of text locator
  • Switch to contains() from exact text() method
  • Combine with more stable properties like test-id

Frequently Asked Questions on Text Locators

Q: Which text locator is better – text() or contains()?

Use text() when text is static and unique. For dynamic text or regional variants, contains() works better. Ultimately both used together provide more stability.

Q: Can I use text from child span/div within parent node?

It‘s best to match exact text from direct parent element encompassing the child node for reliability.

Q: Is performance of text locators slower than ID/Class based?

JavaScript DOM lookups for text tend to be marginally slower but with modern browsers the difference is negligible in most cases.

Q: What are the key advantages Text locator has over LinkText locator?

Text locator is versatile matching any element text vs just link texts. Also text locators allow partial matches using contains() unlike LinkText.

Conclusion

This brings us to the end of our complete guide on using text locators in test automation. The key takeaways are:

✅ Text locators help deal with dynamic attributes and localized text differences
✅ Use text() for static unchanging text and contains() for dynamic text
✅ Combine text locators with automation-id and data attributes for added reliability
✅ Implement tips around parameterization and search context for stable locators

Accurate element identification is key to producing reliable test automation for modern web apps. In that context, text locators form an indispensable technique for all test engineers working with Selenium.

Hope this guide helps you adopt text locators widely in your test automation framework. Happy testing!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.