XPath Contains Text in Selenium Explained with Examples


Locating elements accurately is one of the most important aspects of building reliable Selenium automation scripts. While IDs and CSS selectors are commonly used, many applications rely heavily on visible text for navigation and interactions.
XPath provides flexible functions like text() and contains() that help testers locate elements based on exact or partial text matches.
Mastering these techniques is essential for handling real-world scenarios where attributes are dynamic or unavailable.
What is XPath contains() in Selenium?
XPath is a query language that allows navigation through elements and attributes of XML documents, including HTML. The contains() function in XPath is particularly useful in
Selenium to match elements whose attribute values or text partially match a given string. Instead of relying on static IDs or long class names, contains() can be used to locate elements with flexible patterns.
For example:
//button[contains(text(),'Login')]This finds any <button> element whose text contains the word “Login”.
Difference Between text() and contains() in XPath
Understanding the difference between these two approaches ensures that you use the right locator in each situation:
- text(): Matches the element text exactly. If there is any extra space or variation in case, the match will fail.
- contains(): Matches partial values, making it more robust for dynamic content or when exact text isn’t known.
Example with text():
//h1[text()='Welcome User']This works only if the element text is exactly “Welcome User”.
Example with contains():
//h1[contains(text(),'Welcome')]This matches “Welcome User”, “Welcome Back”, or any similar variation.
Find Element by Exact Text Using text() in Selenium
When working with elements that have stable and predictable labels, the text() function is best suited.
Example in Java:
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
WebElement header = driver.findElement(By.xpath("//h1[text()='Welcome User']"));
System.out.println(header.getText());Here, Selenium locates the header element with exact text “Welcome User”. This is reliable when dealing with static headings or button labels.
Find Element by Partial Text Using contains() in Selenium
Web applications often have dynamic or changing content. In such cases, contains() makes XPath more flexible by allowing partial matches.
Example in Java:
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
WebElement loginBtn = driver.findElement(By.xpath("//button[contains(text(),'Login')]"));
loginBtn.click();Even if the button says “Login Now” or “Login Here”, this XPath successfully finds the element.
How to Combine contains() with Other Attributes in XPath
XPath’s contains() is not limited to text. It can also be used with attributes like id, class, or href.
Example:
//input[contains(@id,'username')]This locates an input field where the id contains the word “username”, such as “user_name_field” or “login_username”.
Java example:
WebElement username = driver.findElement(By.xpath("//input[contains(@id,'username')]"));
username.sendKeys("testuser");This approach is powerful when applications use dynamically generated IDs with predictable substrings.
Practical Examples of Using contains text in Selenium
Some real-world use cases where contains() is invaluable:
- Locating dynamic links
//a[contains(text(),'Read More')]This matches links like “Read More”, “Read More Articles”, or “Read More Here”.
- Handling changing button labels
//button[contains(text(),'Submit')]Matches “Submit”, “Submit Form”, or “Submit Details”.
- Finding elements with dynamic class names
//div[contains(@class,'alert')]Captures elements with class names like “alert-danger”, “alert-success”, or “alert-warning”.
Common Mistakes and How to Avoid Them in XPath Text Matching
While using contains text in Selenium, testers often make mistakes that lead to unreliable locators:
- Over-reliance on partial matches: Using overly generic text like “a[contains(text(),’Click’)]” can return multiple elements. Always make the condition specific.
- Ignoring whitespace: Extra spaces in text can break text() locators. Use normalize-space(text()) to handle trimming.
- Not escaping quotes: If the text includes both single and double quotes, use concat() in XPath.
Example handling whitespace:
//span[normalize-space(text())='Submit']Best Practices for Writing Stable XPaths with contains text
To maximize stability of Selenium locators, follow these best practices:
- Prefer unique identifiers when available: Use id or name over text when possible.
- Use contains() only for dynamic or unpredictable content: Avoid partial matches unless necessary.
- Combine text with attributes: Make locators stronger by combining contains(text(),…) with attributes like @class.
- Keep XPaths short and readable: Avoid deeply nested expressions that break easily with small DOM changes.
Example of combining conditions:
//button[contains(text(),'Login') and contains(@class,'btn-primary')]Why Run XPath-Based Tests on Real Devices and Browsers?
XPath expressions often behave differently across browsers due to variations in DOM rendering and whitespace handling. Testing only on local environments can miss browser-specific issues.
Running tests on a real device cloud like BrowserStack Automate allows teams to validate XPath locators across thousands of real browsers and operating systems. This ensures that locators built with contains text perform consistently in real-world conditions, reducing flakiness and improving confidence in automation.
Conclusion
XPath contains() and text() functions are essential tools in Selenium for locating elements based on visible text. While text() is best for exact matches, contains() provides flexibility for partial or dynamic content.
Combining them with attributes and following best practices ensures robust and maintainable locators. For maximum reliability, always validate these XPath strategies on real browsers and devices using platforms like BrowserStack Automate.

Contents
- What is XPath contains() in Selenium?
- Difference Between text() and contains() in XPath
- Find Element by Exact Text Using text() in Selenium
- Find Element by Partial Text Using contains() in Selenium
- How to Combine contains() with Other Attributes in XPath
- Practical Examples of Using contains text in Selenium
- Common Mistakes and How to Avoid Them in XPath Text Matching
- Best Practices for Writing Stable XPaths with contains text
- Why Run XPath-Based Tests on Real Devices and Browsers?
- Conclusion
Subscribe for latest updates
Share this article
Related posts













