Writing Effective XPath Expressions
What Makes an XPath Expression
XPath is a query language for navigating XML and HTML documents. It lets you locate elements based on their tag, attributes, text content, or position relative to other elements in the page structure.
Absolute vs Relative XPath
An absolute XPath starts from the root of the document and traces the full path to an element, making it extremely fragile to any structural change. A relative XPath starts from anywhere in the document, making it far more resilient and the recommended approach.
- Absolute XPath example pattern: /html/body/div/form/input
- Relative XPath example pattern: //input[@id='username']
- Relative XPath is preferred for nearly all real-world automation
Useful XPath Functions
| Function | Purpose |
|---|---|
| contains() | Matches elements whose attribute or text partially matches |
| text() | Matches elements based on their visible text content |
| starts-with() | Matches attributes that begin with a given value |
| following-sibling / preceding-sibling | Navigates relative to sibling elements |
Writing Readable, Resilient XPath
Keep expressions as short as possible, anchor them to meaningful attributes rather than layout, and avoid chaining too many nested conditions, which becomes hard to read and easy to break during future UI updates.
Ready to master Selenium Training Course?
Join Uncodemy's hands-on training and build real automation skills with expert mentors.
← Back to Course