Skip to content

CSS Selectors vs XPath

diagram CSS selectors and XPath overlap, and then diverge mermaid
For everyday selection they do the same job and CSS is shorter. XPath earns its verbosity in two places CSS cannot reach: matching on the text a node contains, and walking back up to a parent or an earlier sibling. If a selector needs either of those, that is the moment to switch.

Great for:

  • BeautifulSoup (select, select_one)
  • Playwright
  • browser devtools

Examples:

  • .price
  • div.card a
  • #main h2.title

Great for:

  • lxml
  • Selenium (via XPath)
  • complex DOM relationships

Examples:

  • //div[@class='card']//a
  • //table//tr[1]/td[2]
  • CSS is usually simpler
  • XPath is more powerful for “go to parent/sibling” cases

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading