Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 35 ยท Finding Elements

XPath Locators

Learn XPath for Selenium: absolute and relative paths, predicates, text() and contains(), and axes to reach parents and siblings, with runnable examples.

XPath is a query language for tree-shaped documents. A web page is exactly that: a tree of elements. Where CSS selectors describe elements by their tag, class and attributes, XPath can do two things CSS cannot: match an element by its text, and walk up and sideways through the tree (to a parent, or to the cell next to a label).

Because of that, XPath is the right second tool. You will not use it for every locator, since CSS is shorter and faster for most, but it solves the cases CSS can't. In Selenium it is By.XPATH, and the Selenium calls here are read-only. The stand-ins use document.evaluate, the browser's own XPath engine, so the expressions you test are real XPath.

Python
from selenium.webdriver.common.by import By

driver.find_element(By.XPATH, "//button[text()='Save']")

Absolute and relative paths

An XPath expression is a path through the tree, written with slashes.

  • A single slash / goes one level down. An absolute path starts at the root: /html/body/div[2]/form/input[1].
  • A double slash // means "anywhere below". A relative path starts with it: //input.

Absolute versus relative

Absolute: /html/body/div[2]/button Every level spelled out. Breaks when the layout changes.
Relative: //button[@id='save'] Jumps to what matters. Survives layout changes.

Avoid absolute paths in real tests.

1 / 2

Absolute paths, and the long ones you get when copying "Copy XPath" from DevTools, break the moment a designer wraps something in a new div. Write short relative paths anchored on something meaningful instead.

The pieces of an expression

Syntax Meaning Example
//tag Any element of that tag //button
//* Any element //*[@id='x']
@attr An attribute //input[@type='email']
[1] The first match (XPath counts from 1) (//li)[1]
[last()] The last match (//li)[last()]
text() The element's own text node //a[text()='Home']
. The element's whole text //a[.='Home']
.. The parent //input[@id='q']/..

Predicates

A predicate is a condition in square brackets that filters the matches. Combine conditions with and, or and not():

TEXT
//input[@type='text' and @name='q']
//button[not(@disabled)]
//a[@href and @class='doc']

Matching text

TEXT
//button[text()='Save']                     exact own text
//button[normalize-space()='Save']          ignores extra spaces and newlines
//a[contains(text(), 'Guide')]              text contains
//a[contains(@href, 'files')]               attribute contains
//a[starts-with(@href, 'https')]            attribute starts with

Exact text()='Save' fails when the HTML has stray spaces or line breaks around the text, so normalize-space() is a safer habit. Use . instead of text() when the visible text is split across child elements, such as <button>Save <b>now</b></button>.

Positions: counting from one

XPath positions start at 1, not 0. //li[1] means "every li that is the first child li of its parent", which can match several elements. To get the first match in the whole document, wrap it: (//li)[1].

Axes: moving around the tree

An axis says in which direction to move from the current element. They are what let XPath find an element by its neighbors.

Axis Moves to
parent:: (or ..) The parent
ancestor:: Every ancestor up to the root
child:: (default) Direct children
descendant:: All descendants (what // uses)
following-sibling:: Later siblings
preceding-sibling:: Earlier siblings

A common use is a table where the only way to find the right button is through the text in the same row:

TEXT
//td[text()='Ada']/following-sibling::td/button
//td[text()='Ada']/parent::tr//button[text()='Delete']

A stand-in: running XPath with document.evaluate

The helper below wraps document.evaluate and prints what each expression finds. It builds a small table and a form, then runs the expressions from this lesson. Everything here is real XPath evaluated by the browser's engine.

JS XPath expressions on a sample page

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice three results. //button[text()='Save'] finds nothing, because the button's text is " Save " with spaces; normalize-space() finds it. //button matches seven buttons, and (//button)[1] picks exactly one. And the row-based expressions find Grace's Delete button even though it has no id of its own.

The leading-dot trap

When you call find_element on an element, a locator starting with // still searches the whole document, not just inside that element. To search inside, start with a dot:

Python
row = driver.find_element(By.XPATH, "//tr[td[text()='Ada']]")
row.find_element(By.XPATH, ".//button[text()='Delete']")   # inside the row
row.find_element(By.XPATH, "//button[text()='Delete']")    # whole page: the FIRST Delete anywhere

The stand-in below shows the difference using the same table.

JS Searching inside a row: .// versus //

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The // version returns both buttons and find_element would hand you the first one: Ada's, not Grace's. That is a classic bug that deletes the wrong record.

When to use XPath, and when not to

Use XPath when you need:

  • an element by its visible text (a link or button without a good attribute);
  • an element relative to another (the input next to a label, the button in the row that contains a name);
  • to move up to a parent.

Prefer CSS for everything else. XPath expressions are easy to over-engineer: long chains of div[3]/span[2] are as brittle as absolute paths. Anchor on text or attributes that mean something, and keep expressions short. Which locators survive redesigns is covered in Choosing Stable Locators.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which XPath returns the first li in the whole document?

    //li[1] means every li that is the first li child of its parent, which can match several. Wrapping in parentheses first collects all li elements, then [1] picks one. XPath positions start at 1, not 0.
  2. 2. Why does //button[text()='Save'] sometimes find nothing even though the page shows Save?

    text()='Save' needs an exact match of the text node. Whitespace around the word breaks it, while normalize-space() trims and collapses it.
  3. 3. You call row.find_element(By.XPATH, "//button") on a row element. What gets searched?

    A path starting with // searches from the document root even when called on an element. Use .//button to search inside the row.
  4. 4. Which of these can XPath do but a CSS selector cannot?

    CSS has no text matching and cannot go up to a parent in a locator. XPath has text(), contains() and axes like parent:: for exactly that.
  5. 5. Why are absolute XPaths like /html/body/div[2]/form/input[1] a poor choice?

    An absolute path encodes every level of the layout. Any wrapper added or removed along the way makes the locator fail.

Summary

  • XPath is a query language for the page tree; in Selenium it is By.XPATH.
  • // starts a relative path, / goes one level down; avoid long absolute paths.
  • Predicates filter by attribute, position (counting from 1), contains(), starts-with() and normalize-space().
  • Axes such as parent::, following-sibling:: and ancestor:: let you find elements by their neighbors.
  • Inside an element, start with .// or the search jumps to the whole document.
  • Use XPath for text and relationships; prefer CSS for everything else.
  • The document.evaluate examples run real XPath in your browser; Selenium itself is read-only here.

Next, learn how to choose locators that last in Choosing Stable Locators.