XPath Cheat Sheet for Selenium: 30 Locators with Examples
Thirty practical XPath locators for Selenium, from basic attributes to axes and dynamic tables, with Java examples and DevTools tips.
IDs are great when developers add them. Real applications are messier: auto-generated class names, tables with no unique attributes, buttons that only differ by the row they sit in. That is when XPath earns its place. This XPath cheat sheet collects 30 locators that solve the problems testers actually hit in Selenium projects, each with a one-line explanation.
Bookmark it, keep DevTools open, and try each expression against a page you test daily. The goal is not to memorise syntax but to recognise which pattern fits which problem, so you can write locators that survive the next UI change.
Key takeaways
- Prefer ID, name or a stable CSS selector first; use XPath when you need text matching or to move up and across the DOM.
- Browsers support XPath 1.0 only, so functions like
ends-with()andmatches()will not work in Selenium. - Relative XPath anchored on stable text or attributes is far more robust than absolute paths.
- Axes such as
following-sibling,ancestorandprecedingsolve most “no unique attribute” problems. - Always validate an XPath in DevTools before putting it in code, and make sure it matches exactly one element.
The sample HTML used in this XPath cheat sheet
Most examples below refer to this simplified login and orders page:
<form id="login-form">
<label for="email">Email</label>
<input id="email" name="email" type="text" class="form-control input-lg">
<label for="pwd">Password</label>
<input id="pwd" name="password" type="password" class="form-control">
<label><input type="checkbox" name="remember"> Remember me</label>
<button type="submit" class="btn btn-primary"> Login </button>
</form>
<table id="orders">
<tr><th>Order</th><th>Customer</th><th>Status</th><th>Action</th></tr>
<tr><td>ORD-1041</td><td>Rahul Sharma</td><td>Shipped</td><td><button>View</button></td></tr>
<tr><td>ORD-1042</td><td>Priya Nair</td><td>Pending</td><td><button>Cancel</button></td></tr>
</table>The names are invented for illustration. Adapt the patterns to your own application’s DOM.
How to use XPath in Selenium 4 with Java
In Selenium you pass the expression to By.xpath():
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;
public class XPathDemo {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.get("https://example.com/login");
WebElement email = driver.findElement(By.xpath("//input[@id='email']"));
email.sendKeys("tester@example.com");
List<WebElement> rows = driver.findElements(By.xpath("//table[@id='orders']//tr[td]"));
System.out.println("Order rows: " + rows.size());
} finally {
driver.quit();
}
}
}Selenium Manager (built into Selenium 4.6 and later) downloads a matching driver automatically, so you do not need to set a driver path. Replace the URL with your application under test. If you are just starting, our Selenium WebDriver tutorial covers project setup step by step.
Basic XPath locators (1-10)
- 1. Absolute XPath:
/html/body/form/input[1]starts at the root. It breaks whenever layout changes, so avoid it except for quick experiments. - 2. Relative XPath by attribute:
//input[@id='email']finds an input anywhere in the page with that id. This is the basic building block. - 3. Any tag with an attribute:
//*[@name='password']matches any element type. Useful when the tag might change, but slightly slower on large pages. - 4. Two attributes with and:
//input[@type='text' and @name='email']narrows matches when one attribute is not unique. - 5. Either attribute with or:
//input[@id='email' or @name='email']helps when different builds use different attributes. - 6. Exact text:
//button[text()='Login']fails on our sample because the button text has extra spaces. That surprise is common. - 7. Text with spaces trimmed:
//button[normalize-space()='Login']trims leading and trailing spaces and collapses inner spaces. Prefer this overtext()for buttons and links. - 8. Partial attribute:
//input[contains(@class,'input-lg')]matches when the class list contains that string. - 9. Partial text:
//td[contains(text(),'Sharma')]matches cells that include the substring. - 10. Prefix match:
//input[starts-with(@id,'user_')]handles dynamic ids such asuser_8731where only the prefix is stable.
Intermediate XPath locators (11-17)
- 11. Ends-with workaround:
//input[substring(@id, string-length(@id) - string-length('_name') + 1) = '_name']. XPath 1.0 has noends-with(), so this substring trick does the job. - 12. Negation:
//input[not(@disabled)]finds enabled inputs. Also useful://button[not(contains(@class,'hidden'))]. - 13. Index on a result set:
(//input[@type='checkbox'])[2]returns the second checkbox in the whole page. Without brackets,//input[2]means “the second input child of its parent”, which is a different thing and a classic interview question. - 14. Last element:
(//table[@id='orders']//tr)[last()]returns the last row. - 15. Position range:
//table[@id='orders']//tr[position()>1]skips the header row. - 16. Exact class token:
//input[contains(concat(' ', normalize-space(@class), ' '), ' form-control ')]avoids matchingform-control-lgwhen you need the exact class. - 17. Case-insensitive text:
//button[translate(normalize-space(),'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='login']. XPath 1.0 has nolower-case(), sotranslate()is the standard workaround.
XPath axes locators (18-25)
Axes let you move from an element you can find reliably to the one you actually need. The default axis is child, which is why / means “direct child”.
- 18. Parent:
//td[text()='Priya Nair']/parent::tr(short form:/..) gets the row containing a cell. - 19. Ancestor:
//input[@id='email']/ancestor::formfinds the enclosing form at any level above. - 20. Descendant:
//table[@id='orders']/descendant::buttonreturns every button inside the table, however deep. - 21. Following sibling:
//label[text()='Email']/following-sibling::input[1]gets the input right after a label. Very useful for forms with no ids. - 22. Preceding sibling:
//td[text()='Pending']/preceding-sibling::td[2]moves left two cells to reach the order number. - 23. Following:
//label[text()='Password']/following::input[1]gets the first input anywhere after the label in document order, not only siblings. - 24. Preceding:
//button[normalize-space()='Login']/preceding::input[1]gets the input just before the button. - 25. Self with condition:
//td[text()='Shipped']/self::tdis rarely needed alone, but helps in combined expressions and appears in interviews.
Real-world XPath patterns (26-30)
- 26. Cell by row text:
//table[@id='orders']//tr[td[normalize-space()='ORD-1042']]/td[3]returns the status of a specific order. The innertd[...]filter selects the row. - 27. Button in a matching row:
//tr[td[normalize-space()='ORD-1042']]//button[normalize-space()='Cancel']clicks an action for one record without relying on row index. - 28. Checkbox by its label text:
//label[normalize-space()='Remember me']/inputworks when the input sits inside the label. - 29. SVG elements:
//*[local-name()='svg']//*[local-name()='path']. SVG lives in a different namespace, so plain//svgusually returns nothing. - 30. Union of two locators:
//input[@name='email'] | //input[@name='username']returns matches from either expression, handy when two versions of a page coexist.
Writing dynamic XPath in code
Hard-coding values inside locators makes page objects rigid. Build them from parameters instead:
import org.openqa.selenium.By;
public final class OrderLocators {
private OrderLocators() {}
public static By actionButton(String orderId, String action) {
return By.xpath(String.format(
"//tr[td[normalize-space()='%s']]//button[normalize-space()='%s']", orderId, action));
}
public static By statusCell(String orderId) {
return By.xpath(String.format(
"//table[@id='orders']//tr[td[normalize-space()='%s']]/td[3]", orderId));
}
}Usage: driver.findElement(OrderLocators.actionButton("ORD-1042", "Cancel")).click();
This pattern fits neatly inside a Page Object Model class and keeps test methods readable.
Text containing an apostrophe
A value like “Don’t save” breaks single-quoted XPath. Use concat():
By dontSave = By.xpath("//button[normalize-space()=concat('Don', \"'\", 't save')]");Searching inside an element: the dot matters
This is one of the most common XPath bugs in Selenium code:
WebElement row = driver.findElement(By.xpath("//tr[td[normalize-space()='ORD-1042']]"));
WebElement wrong = row.findElement(By.xpath("//button")); // searches the WHOLE page
WebElement right = row.findElement(By.xpath(".//button")); // searches inside the row onlyAn expression starting with // always begins from the document root, even when called on a WebElement. Start with .// to stay inside the element.
How to test XPath quickly in Chrome DevTools
- Open DevTools (F12) and go to the Elements panel.
- Press Ctrl+F (Cmd+F on Mac) and paste your XPath. Chrome shows how many nodes match, such as “1 of 1”.
- Or open the Console and run
$x("//button[normalize-space()='Login']"), which returns an array of matching elements. - Aim for exactly one match. If you get more, add a condition or anchor on a nearby stable element.
Two exceptions tell you different things. InvalidSelectorException means the expression itself is broken, often a missing bracket or an XPath 2.0 function. NoSuchElementException means the syntax is fine but nothing matched at that moment, which is frequently a timing problem rather than a bad locator. Wrap such lookups in an explicit wait before you start rewriting the XPath.
XPath vs CSS selectors: when to use which
| Need | Better choice |
|---|---|
| Unique id, name or class | CSS or By.id |
| Match by visible text | XPath |
| Move to parent or ancestor | XPath |
| Sibling to the right | Either (CSS has + and ~) |
| Sibling to the left | XPath |
| Speed and readability for simple cases | CSS |
Both are first-class in Selenium. The official Selenium documentation lists all locator strategies. Interviewers often ask this comparison, so check our Selenium interview questions for model answers. If you are evaluating other tools, Playwright prefers role and text locators over XPath, as explained in Playwright vs Selenium vs Cypress.
Checklist for robust XPath
- Anchor on stable attributes such as id, name, data-testid or aria-label.
- Use
normalize-space()instead oftext()for visible text. - Avoid absolute paths and long index chains like
div[3]/div[2]/span[1]. - Avoid auto-generated classes such as
css-1x2y3z. - Keep locators in page classes, not scattered in tests.
- Ask developers to add
data-testidattributes for critical elements.
🚀 Looking for Selenium automation jobs?
QA Jobs India shares 100+ fresh QA & software testing openings every morning — manual, automation, API and remote roles.
See today’s QA jobs →Selenium jobs by city: Selenium tester jobs in Chennai – skills, interview rounds, 7-day plan · Automation testing jobs in Bangalore · SDET jobs in Hyderabad. Next locator round in your interview is often API: 25 Postman interview questions.
FAQs
What is the difference between single slash and double slash in XPath?
A single slash selects a direct child of the current node. A double slash selects matching nodes at any depth below the current node. //form/input finds inputs directly under a form, while //form//input finds inputs anywhere inside it.
Does Selenium support XPath 2.0?
No. Selenium uses the browser’s XPath engine, and browsers implement XPath 1.0. Functions like ends-with(), matches() and lower-case() will throw errors, so use workarounds such as substring() and translate().
Is XPath slower than CSS selectors?
In modern browsers the difference is usually small and rarely the cause of slow tests. Choose the locator that is most stable and readable. Waits and test design affect speed far more.
How do I handle dynamic IDs with XPath?
Use starts-with() or contains() on the stable part of the id, or anchor on nearby visible text with an axis like following-sibling. Best of all, ask developers for a stable data-testid attribute.
Should I copy XPath from the browser’s “Copy XPath” option?
Treat it as a starting point only. Browser-generated XPath often depends on positions and breaks easily. Rewrite it using attributes, text and axes from this cheat sheet.
Conclusion
Good XPath is about choosing a stable anchor and moving from it with the right axis. Pick five locators from your current project that rely on indexes or absolute paths, rewrite them using patterns from this XPath cheat sheet, and verify each one in DevTools. Your tests will fail less often for reasons that have nothing to do with real bugs.
- 100+ fresh QA jobs daily + Direct HR email IDsLive every morning at 9 AM — apply straight to HR
- Weekly Mega Job Fair800+ QA jobs from India & around the world, every week
- Certified QA coursesUp to 3 courses included · all 17 for ₹500
- AI ATS Resume BuilderFree resume points included
- Full LinkedQA feedEvery post, fully unblurred
- Complete QA Material libraryInterview Q&A, cheat sheets, templates & roadmaps
Instant activation right after payment · One login for jobs, courses, resume & LinkedQA
💎 Get every QA opening, every day
Join QA Jobs India Premium for 100+ verified QA jobs daily with HR contact details.
QA Jobs Hub
Every QA job opening, company profile and career guide on QA Jobs India — India & Global, in one place.