Guide

XPath vs CSS selectors

CSS selectors are fast and native to the browser; XPath can walk up to parents, sideways to siblings, and filter by text content. This guide compares the two languages for web scraping and testing, with runnable XPath examples you can open in the Sandbox.

What CSS selectors do best

CSS selectors are built for styling, so every modern browser optimises them for speed. They are the native language of Playwright, Puppeteer, Selenium, and Cypress, which makes them the right default for most UI tests.

  • Fast, browser-native evaluation.
  • Concise class, id, and attribute matching.
  • Pseudo-classes for state: :checked, :disabled, :nth-child(2).
  • No learning curve if you already write stylesheets.

Where XPath pulls ahead

XPath was designed to navigate XML trees. It can move up to parents and ancestors, sideways to siblings, and filter by the text content inside a node — relationships CSS selectors cannot express.

  • Parent and ancestor traversal: ancestor::form, parent::tr.
  • Sibling traversal: preceding-sibling::label, following-sibling::*.
  • Text-content matching: //button[contains(., 'Submit')].
  • Arbitrary predicates and functions: //item[position() > 1], normalize-space(.).

CSS vs XPath at a glance

The table below shows common locator patterns side by side. Where only XPath appears, you are looking at a tree relationship CSS cannot express.

CSS selectors and XPath equivalents
TaskCSS selectorXPath
By id#work//*[@id='work']
By class.project//*[contains(@class, 'project')]
By attribute[data-testid='hero']//*[@data-testid='hero']
Childsection > h2//section/h2
Descendantsection h2//section//h2
First childli:first-child//li[1]
Parentnot possible//h2/parent::*
Ancestornot possible//span/ancestor::form
Preceding siblingnot possible//input/preceding-sibling::label
Text contentnot possible (native CSS)//a[contains(., 'Home')]

Try it in the Sandbox

Open any example in the Sandbox to run it against the built-in XHTML sample. Tweak the expression, then copy it into your scraper or test suite.

XPath tester · XPath axes reference · Free XPath course