Glossary
XPath: navigating the document tree
XPath is a query language that selects nodes in an XML or HTML tree using paths, conditions and directional axes.
Definition
XPath was created for XML and works on HTML once it is parsed into a tree. An expression describes a route through the tree, like a file path, plus optional conditions in square brackets. Version 1.0 is what browsers, lxml, Scrapy, Selenium and Playwright support, so stick to its functions when portability matters.
Paths and predicates
/html/body/div: an absolute path from the root (brittle, avoid).//table: every table anywhere in the document.//div[@class="offer"]: divs whose class attribute is exactly "offer".//div[contains(@class, "offer")]: divs whose class contains the substring.//ul/li[1]: the firstliof each list (XPath counts from 1).//a/@href: the href attribute values themselves.//h1/text(): the direct text nodes of headings.
Watch the class trap: @class="offer" fails on class="offer featured". The robust form is contains(concat(" ", normalize-space(@class), " "), " offer "), which is long but exact.
Axes
Axes are what set XPath apart. They let you move in any direction from a node:
| Axis | Moves to |
|---|---|
parent:: | The node's parent |
ancestor:: | Any node above it |
following-sibling:: | Siblings after it |
preceding-sibling:: | Siblings before it |
descendant:: | Any node below it |
When XPath beats CSS selectors
- Matching by text.
//button[normalize-space()="Load more"]finds a button by its label. - Label and value pairs.
//th[normalize-space()="Weight"]/following-sibling::td[1]reads a spec table cell by its header, regardless of row order. - Going up.
//span[@class="sale"]/ancestor::articleselects the card that contains a sale badge. - Conditions on children.
//li[.//img]keeps only items that contain an image.
For simple class and attribute lookups, CSS selectors are shorter and easier to read. Many teams mix both in one scraper.
Example with lxml
from lxml import html
tree = html.fromstring(spec_page)
spec = {}
for row in tree.xpath('//table[@id="specs"]//tr[th and td]'):
key = row.xpath("normalize-space(th)")
spec[key] = row.xpath("normalize-space(td[1])")
print(spec.get("Weight"), spec.get("Battery"))
Calling normalize-space() inside the expression returns a trimmed string directly, so there is no separate cleanup step.
Debugging an expression
Browser developer tools evaluate XPath directly: in the console, $x('//th[normalize-space()="Weight"]') returns the matching nodes in Chrome and Firefox. Build the expression piece by piece, checking the match count after each predicate. Remember that the browser shows the live DOM, so an expression that works there can fail on raw HTML that scripts have not yet filled.
XPath and CAPTCHA detection
A single expression can tell you whether a challenge is present and pull its key: //*[@data-sitekey]/@data-sitekey returns the site key of a reCAPTCHA v2, Cloudflare Turnstile or similar widget wherever it sits. If it returns a value, send it with the page URL as a task, then continue with the real page once the answer is submitted. The select by text answer has more text matching patterns.
Common questions
Does XPath work on HTML or only XML?
It works on HTML once a parser has built a tree, which is what lxml, Scrapy, Selenium and browsers do.
Why does XPath index from 1?
The specification counts positions from 1, so li[1] is the first item, unlike zero based arrays in most languages.
Can Beautiful Soup run XPath?
Not directly. Parse with lxml for XPath, or use CSS selectors with Beautiful Soup.
How do I select an element by its visible text?
Use a predicate with normalize-space(), for example an a element whose normalized text equals the label you want.
Which XPath version should I write?
XPath 1.0, because it is the version supported by browsers and the common scraping libraries.
Keep reading
- CSS selectorCSS selectors are the compact pattern language for picking elements by tag, class, attribute and position, and most scraping tools speak it.
- HTML parsingHTML parsing turns markup into a tree your code can query, and tolerant parsers rebuild broken pages the same way browsers do.
- How do I select elements by their text with XPath?Use text() for exact matches and contains() or normalize-space() for loose ones, and anchor the path on the element type.
- How do I select sibling elements in XPath?The following-sibling and preceding-sibling axes walk sideways from an anchor, ideal for label and value pairs in tables and lists.