Or copy link
When automating web applications, you often need to locate elements based on the exact text they contain. XPath provides a powerful way to capture elements by their exact text content using the text() function. This method is particularly useful for targeting elements like headings, buttons, links, or labels where the text is static and unique.
text()
The text() function in XPath allows you to access the visible text of an element. By matching the exact text value of an element, you can precisely locate it in the DOM. This is ideal for elements where text is the defining characteristic.
The basic syntax for locating an element by its text is:
//tagname[text()='exact text']
tagname
div
span
button
'exact text'
If the text is unique to the element, this method provides an efficient and straightforward way to find it.
Buttons often have specific text that makes them easy to identify. Let’s locate a button with exact text.
DOM Example:
Login
XPath Solution:
//button[text()='Login']
Explanation:The XPath expression //button[text()='Login'] selects the button element whose visible text is exactly “Login”. This approach ensures you target the correct button.
Headings like h1, h2, or h3 often have meaningful and unique text. You can use their text content to locate them accurately.
h1
h2
h3
Welcome to Our Website
//h1[text()='Welcome to Our Website']
Explanation:The XPath //h1[text()='Welcome to Our Website'] targets the h1 element with the exact text “Welcome to Our Website”. This method is especially useful for verifying static page content.
Case Sensitivity: XPath is case-sensitive. Ensure the text in your XPath matches the case exactly as it appears in the DOM. For example, “Login” is different from “login”.
Whitespace Sensitivity: Leading, trailing, or extra spaces in the text can cause the match to fail. If the text contains unpredictable spaces, consider using the normalize-space() function for better results.
normalize-space()
Dynamic Text: Avoid using exact text matching for dynamic or localized content, as it may change based on user settings or translations.
Using XPath to capture elements by their exact text content is a precise and effective method for locating static elements in the DOM. By leveraging the text() function, you can target elements with unique and unchanging text, making your XPath expressions both efficient and reliable.
Master this technique to write clean and maintainable XPath expressions for your automation scripts. Let me know if you’d like additional examples or enhancements!
XPath is a powerful tool for locating elements on a web...
In Selenium automation, XPath is a powerful method for ...
Save my name, email, and website in this browser for the next time I comment.
Δ