Glossary · UI automation
XPath
Also called: XPath expression, XPath expressions, XPaths, XPath locator
Definition
A query language for selecting nodes in an XML or HTML document, used in UI automation to locate elements by structure, attributes or text.
XPath (XML Path Language) describes a path through a document tree to the nodes you want. In test automation it is one of the ways to write a locator, and its main advantage over CSS is that it can match on text content and walk in any direction: up to a parent, across to a sibling, or down to a descendant. Browsers implement XPath 1.0, so functions from later versions, such as matches() or lower-case(), are not available.
Example
//button[normalize-space()='Sign in']
//input[@name='email']
//label[text()='Password']/following-sibling::input
//tr[td[normalize-space()='Order 1042']]//button[@aria-label='Cancel']
//a[contains(@href, '/invoices/')]
The fourth line shows why people reach for XPath: find the table row that contains a given cell, then the button inside that row.
WebElement cancel = driver.findElement(
By.xpath("//tr[td[normalize-space()='Order 1042']]//button[@aria-label='Cancel']"));
Absolute versus relative
An absolute XPath starts at the root (/html/body/div[2]/form/button) and breaks as soon as any wrapper changes. A relative XPath starts with // and anchors on something meaningful. Copying the “full XPath” from DevTools gives you the absolute form, which is almost never what you want in a test.
Common mistakes
- Index-based paths such as
(//div)[7]. They encode layout, not meaning. text()on elements with nested markup.//button[text()='Save']fails if the label sits in a child<span>.normalize-space()(or.) uses the full string value instead.- Matching a class with
@class='btn'. That only matches whenbtnis the entire attribute. Usecontains(concat(' ', normalize-space(@class), ' '), ' btn '), or switch to CSS.btn. - Defaulting to XPath out of habit. In Playwright,
getByRoleandgetByTextcover most text-based cases and read better.