CSS Selectors vs XPath
flowchart LR
subgraph "both do this"
A["by tag, class, id"]
B["descendant and child"]
C["attribute equals / contains"]
D["nth child"]
end
subgraph "only XPath"
E["match on text content"]
F["walk UP to a parent"]
G["preceding sibling"]
H["arbitrary boolean logic"]
end
A --> I["prefer CSS -- shorter, and the same syntax as your stylesheets"]
E --> J["prefer XPath -- 'the row whose label says Total'"]
F --> J
CSS selectors
Section titled “CSS selectors”Great for:
- BeautifulSoup (
select,select_one) - Playwright
- browser devtools
Examples:
.pricediv.card a#main h2.title
Great for:
- lxml
- Selenium (via XPath)
- complex DOM relationships
Examples:
//div[@class='card']//a//table//tr[1]/td[2]
Quick comparison
Section titled “Quick comparison”- CSS is usually simpler
- XPath is more powerful for “go to parent/sibling” cases
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading