XPath (XML Path Language) is a fundamental tool in web automation and testing, allowing developers and testers to navigate through XML and HTML documents to locate elements. Whether you’re working with Selenium, Cypress, or other automation frameworks, understanding how to write and use XPath locators effectively is crucial for identifying elements and interacting with them efficiently.
This XPath Locators Cheat Sheet provides a quick reference guide to help you master the essential XPath expressions and syntax. From basic locators to advanced functions and axes, this cheat sheet is designed to streamline your web automation tasks by offering a handy compilation of common and useful XPath techniques. Whether you’re a beginner or an experienced user, this guide will ensure you have the necessary tools at your fingertips to write optimal and efficient XPath expressions.
Table of Contents
XPath Basics
XPath Pattern
Description
Example
Result
//tagname
Selects all elements of a specific tag
//div
All <div> elements
//tagname[@attribute='value']
Selects elements with a specific attribute
//input[@type='text']
<input> elements with type="text"
//tagname[text()='text']
Selects element with exact text
//button[text()='Submit']
Button with “Submit” text
(//tagname)[1]
Selects the first element in a list
(//input)[1]
First <input> element
(//tagname)[last()]
Selects the last element in a list
(//div[@class='item'])[last()]
Last <div> with class='item'
(//tagname)[n]
Selects the nth element in a list
(//li)[3]
Third <li> element
XPath Functions
XPath Pattern
Description
Example
Result
//tagname[contains(@attribute, 'value')]
Partial match for attribute values
//a[contains(@href, 'login')]
<a> with “login” in href
//tagname[starts-with(@attribute, 'value')]
Matches the beginning of an attribute
//div[starts-with(@class, 'alert')]
<div> with class starting with “alert”
//tagname[contains(text(), 'value')]
Partial text match
//p[contains(text(), 'Welcome')]
<p> with “Welcome” in text
//tagname[normalize-space(text())='value']
Removes leading/trailing spaces
//h2[normalize-space(text())='Title']
<h2> with normalized text “Title”
XPath Logical Operators
XPath Pattern
Description
Example
Result
//tagname[@attribute='value1' or @attribute='value2']
OR condition for multiple attributes
//input[@type='text' or @type='email']
<input> with type="text" or type="email"
//tagname[@attribute1='value1' and @attribute2='value2']