XPath Cheat Sheet: Syntax, Functions, and Examples

xpath cheat sheet

Summarize this blog post with:

When automated tests interact with web elements, they need locators that can reliably identify the intended element without depending on fragile selectors or XPath expressions. Why?

Because even small changes to the page’s DOM structure, attributes, or element hierarchy can cause the locator to stop working and fail the test. XPath gives you a flexible way to describe and locate elements within the DOM.

However, with multiple ways to construct XPath expressions, finding the right syntax can be tricky. That’s why we have created this comprehensive XPath cheat sheet.

It puts together the essential syntax, functions, axes, and practical locator patterns, so your testers can find, adapt, and maintain locators efficiently.

Reduce locator maintenance with TestGrid’s AI-powered auto-healing. Request a free trial.

XPath Cheat Sheet Overview

TL;DR

  • XPath enables precise element identification by combining properties such as attributes, text, position, and DOM relationships
  • Using contains(), starts-with(), normalize-space(), predicates, and indexing create more flexible XPath locators
  • XPath selectors cheat sheet can help you quickly choose the right expression for common element-location scenarios
  • An XPath and CSS selector cheat sheet makes it easy to understand how the two locator approaches differ and when each can be useful for building test automation
  • A Selenium locators cheat sheet can help your testers compare XPath with other Selenium locator strategies when choosing how to identify elements for test automation

What is XPath?

XPath (XML Path Language) is basically a query language that’s used to navigate and select nodes in XML documents and DOM trees representing HTML documents based on their structure, attributes, text, and relationships.

XPath expressions can be used as locator strategies to help automation tools identify elements on a webpage for actions such as clicking, entering text, or verifying content during web automation testing.

XPath also supports selectors, functions, predicates, operators, and axes for precise element queries.

What are the Types of XPath?

1. Absolute

Absolute XPath helps you identify an element by following a complete path from the document’s root node to the target element. It starts with a single ‘/’ and specifies each node along the hierarchy.

This approach can enable you to precisely recognize an element, but it’s fragile and can be hard to maintain because changes to the DOM structure can invalidate the entire XPath expression.

2. Relative

Relative XPath allows you to spot an element without starting from the document’s root node. It generally begins with // and can locate elements based on attributes, text, or their relationships with other nodes.

Since it doesn’t depend on the complete DOM hierarchy, relative XPath is comparatively more flexible and reliable to structural changes in a webpage when it is anchored to stable attributes or relationships.

Learn More: XPath in Selenium

Essential XPath Concepts

1. Syntax and structure

An XPath location path consists of one or more location steps separated by ‘/’. Each step can specify an axis, node test, and optional predicates that filter the selected nodes. Common shorthand includes ‘//’ for descendant-or-self step, ‘@’ for attributes, ‘.’ for the context node, and ‘..’ for its parent.

2. Common functions

XPath functions help you perform operations on strings, numbers, node sets, or Boolean values and can make element selection more precise.

Common functions you can apply for web automation include contains() for partial matching, starts-with() for prefix matching, normalize-space() for handling whitespace, and position() and last() for position-based selection.

The text() node test can also be used to select text nodes when creating XPath expressions.

3. Key axes and nodes

XPath axes define the relationship between a context node and the nodes you want to select, such as its parent, child, ancestor, descendant, or following-sibling. Nodes include elements, attributes, text nodes, comments, processing instructions, and the document/root node.

Axes help you navigate between these nodes and make it possible to locate elements based on their position or relationship within the page structure.

XPath Locators Cheat Sheet: Ways to Find Elements

XPath locators are expressions which tell automation tools how to find specific elements on a webpage. This XPath cheat sheet includes the common locator patterns. This can help your testers choose and adapt the right XPath when creating automated tests.

1. Find element by tag

Select elements by specifying their HTML tag name. This can be useful when you need to target all elements of a particular type, such as buttons, links, or input fields. Since multiple elements can share the same tag, you need to combine the tag with attributes or predicates for a specific match.

XPath expression: //tagname

Example: //button

2. Find element by ID

You can select an element using the value of its id attribute. When an ID is unique within the document, this provides a direct and relatively stable way to locate the element.

XPath expression: //*[@id=’element-id’]

Example: //*[@id=’username’]

3. Find element by class

You can locate an element by matching its class attribute. An exact equality check works when the complete class attribute value is known. However, elements often have multiple classes, so exact matching may become unreliable if additional classes are added or their order changes.

For more reliable matching of a specific class token, use contains() together with normalize-space() to avoid accidentally matching a partial class name.

XPath expression: //*[contains(concat(‘ ‘, normalize-space(@class), ‘ ‘), ‘ class-name ‘)]

Example: //*[contains(concat(‘ ‘, normalize-space(@class), ‘ ‘), ‘ btn-primary ‘)]

4. Find element by attribute

Selecting an element by matching the value of one of its attributes is useful when an element has a distinctive attribute such as name, type, placeholder, aria-label, or data-*.

XPath expression: //*[@attribute=’value’]

Example: //*[@name=’username’]

5. Find element using text

Text-based XPath can be useful when an element has distinctive text content but doesn’t have a reliable ID or other attribute. Using normalize-space(.) allows you to match the element’s text content while handling extra whitespace and text contained within nested elements.

XPath expression: //tagname[normalize-space(.)=’text’]

Example: //button[normalize-space(.)=’Login’]

6. Find element using partial text

contains() is used when text is dynamic or may contain additional words, making an exact text match too restrictive.

XPath expression: //tagname[contains(text(),’partial-text’)]

Example: //button[contains(text(),’Login’)]

7. Find element using partial attributes

Partial attribute matching is helpful when an attribute value is dynamic, contains changing text, or is too long to match reliably in full. XPath’s contains() function lets you match a stable portion of the attribute value instead of requiring an exact match.

XPath expression: //*[contains(@attribute,’partial-value’)]

Example: //input[contains(@id,’user’)]

8. Find elements by their relationships

XPath allows you to locate elements based on their position or relationship to other elements.

This can be particularly helpful when the target element lacks a unique ID, class, or other reliable attribute. You can navigate between related elements with axes like parent, child, following-sibling, and preceding-sibling.

a. By parent

This is used when the target parent has no unique attributes but can be reliably identified through a child element.

XPath expression: //child-element/parent::parent-element

Example: //input[@id=’username’]/parent::div

b. By child

You apply the child axis to locate a child node directly inside a known parent. It enables you to target a specific child when the parent provides a reliable starting point, but the child itself doesn’t have a unique locator.

XPath expression: //parent-element/child::child-element

Example: //div[@id=’login-form’]/child::input

c. By sibling

The following-sibling and preceding-sibling axes are useful when you need to identify an element through another element positioned beside it at the same hierarchy level. They allow you to locate a sibling without relying on the target element having a unique attribute.

XPath expression: //element/following-sibling::sibling-element

Example (preceding sibling): //element/preceding-sibling::sibling-element

Also Read: How to Use CSS Selectors in Selenium WebDriver

XPath Functions Cheat Sheet

XPath functions can help you refine element selection, manipulate or compare values, and evaluate conditions when basic XPath syntax is not sufficient. Here’s a useful XPath query cheat sheet covering common functions for automated testing.

FunctionUseXPath Expression
starts-with()Match an attribute value that begins with a specified string//*[starts-with(@id,’user_’)]
normalize-space()Remove leading or trailing whitespace and collapse consecutive spaces before matching//*[normalize-space(text())=’Login’]
concat()Combine multiple strings or attribute values into one string//*[concat(@id,’-‘,@name)=’user-login’]
substring()Return a substring of a string for matching or comparison//*[substring(@id,1,4)=’user’]
substring-before()Return the part of a string before a specified substring//*[substring-before(@id,’_’)=’user’]
substring-after()Return the part of a string after a specified substring//*[substring-after(@id,’_’)=’login’]
not()Select elements that don’t satisfy a specified condition//*[not(@disabled)]
position()Select an element based on its position within a matching node set(//button)[2]
last()Select the last element in a matching node set(//button)[last()]
count()Count the number of nodes in the node-set selected by an XPath expression//*[count(.//input)=2]

XPath Axes Cheat Sheet

XPath axes help you navigate the relationship between an element and other elements in the DOM. They are useful when a direct locator is not available, and you need to locate an element based on its position or relationship to another element.

AxisUseXPath Expression
ancestorSelect all ancestors of the context element that match the specified element//element/ancestor::ancestor-element
ancestor-or-selfSelect the context element and its matching ancestors//element/ancestor-or-self::element
descendantSelect all matching descendants at any level below the context element//element/descendant::descendant-element
descendant-or-selfSelect the context element and all matching descendants//element/descendant-or-self::element
selfSelect the context element itself if it matches//element/self::element

Learn More: Appium Locator Strategies: A Complete Guide to Finding Elements

Best Practices for Writing Reliable XPath Locators

1. Keep XPath locators compact and readable

It’s best to avoid unnecessarily long XPath expressions with excessive DOM traversal. Selenium recommends keeping locators concise and readable because complex traversal can be hard to maintain and may require more processing.

Pro tip
Aim for the shortest XPath which recognizes the intended element. Try not to reproduce the entire DOM hierarchy when a simpler, stable expression can locate it.

2. Prefer relative XPath

Relative XPath does not start from the document root and is evaluated relative to the current context rather than depending on the document’s root and full DOM hierarchy. This generally helps you produce shorter and more maintainable locators which are less sensitive to structural changes on your web page.

Pro tip
Limit the use of absolute paths such as /html/body/div/…. Opt for concise relative paths like //input[@name=’email’] when it uniquely identifies the intended element.

3. Use stable and unique attributes

When an element has a stable attribute such as an ID or app-specific attribute, use it as the basis of your XPath. Stable attributes are less likely to change when the page structure is modified.

Pro tip
Select attributes which represent the element’s purpose or identity rather than implementation details, because these may change during UI redesigns or code updates. And this can cause locators to become invalid and automated tests to fail.

Also Read: 7 Standard Reasons Why Test Automation Fails [With Solution]

4. Revisit fragile locators

You should regularly review XPath locators that depend on unstable attributes, DOM structure, or positional assumptions. When your app updates, refactoring these locators will allow you to prevent failures and keep your test suite maintainable.

Pro tip
You need to treat locator maintenance as an ongoing task. Reassess failing or frequently modified locators after UI changes. This can minimize repeated test failures.

Build Stable Test Automation with TestGrid

TestGrid is an AI-native test automation platform which supports existing Selenium and Appium test suites across real browsers and mobile devices, with parallel execution and CI/CD integrations including Jenkins, Azure DevOps, and GitHub Actions.

TestGrid also provides AutoHeal capabilities for its codeless test automation. When UI changes affect previously identified elements, AutoHeal can detect locator changes and use alternative locators to help keep tests running.

This can reduce the effort required to maintain tests as your application evolves and minimize test failures caused by changes to UI elements.

Build, run, and scale reliable automated tests with TestGrid. Request a free trial today.

Frequently Asked Questions

What is an XPath cheat sheet for Selenium?

A Selenium XPath cheat sheet is a quick reference for XPath syntax and standard expressions for locating web elements. It usually covers paths, attributes, functions, axes, and practical locator patterns that can be used with Selenium’s By.XPATH() strategy.

What is an XML XPath cheat sheet used for?

An XML XPath cheatsheet gives you the reference syntax for navigating an XML document and selecting specific nodes based on their hierarchy, attributes, relationships, or conditions. It’s helpful when you’re working with XML data, XSLT transformations, or apps that evaluate XPath expressions against XML documents.

Is there a difference between a CSS XPath cheat sheet and an XPath cheat sheet?

Yes. CSS selectors and XPath are separate locator strategies. XPath can navigate the document using axes and select nodes based on their attributes, text, and relationships. CSS selectors use selectors and combinators to select elements based on attributes, hierarchy, and other supported conditions.

What is an XPath injection cheat sheet?

An XPath injection cheat sheet covers the techniques for understanding, testing, and preventing vulnerabilities that can occur when untrusted input is incorporated into dynamically constructed XPath queries. Attackers can manipulate dynamically constructed XPath expressions to alter query results and, depending on the application’s implementation, potentially bypass authorization logic or access unauthorized XML data.

What is the difference between XPath selector cheat sheet and XPath locator cheat sheet?

An XPath selector cheat sheet focuses on XPath expressions and syntax for selecting nodes. An XPath locator cheat sheet emphasizes using those expressions to identify web elements in test automation tools such as Selenium.