Skip to main content
Test Automation

XPath

A query language for selecting elements in HTML/XML documents, commonly used in Selenium for locating web elements.

Full definition

XPath (XML Path Language) is a query language for navigating and selecting nodes in HTML/XML documents. In test automation, it's one of the primary methods for locating web elements.

XPath types:

  • Absolute XPath: Full path from root — `/html/body/div[1]/form/input[2]` (fragile, avoid)
  • Relative XPath: Starts anywhere — `//input[@id='email']` (preferred)

Useful XPath patterns:

  • By attribute: `//input[@name='email']`
  • By text: `//button[text()='Submit']`
  • Contains: `//div[contains(@class, 'error')]`
  • Parent/child: `//div[@class='form']//input`
  • Sibling: `//label[text()='Email']/following-sibling::input`
  • Index: `(//button)[2]` — second button on page

XPath vs CSS selectors:

  • XPath can traverse up the DOM (parent::) — CSS cannot
  • XPath can select by text content — CSS cannot
  • CSS selectors are generally faster
  • CSS syntax is more readable

Best practice: prefer ID and CSS selectors when available, use XPath when you need text-based or parent-traversal selection.

Learn more about xpath in practice

Automation track