# XPath vs CSS selectors, five fields written both ways | Spider

Five fields from one practice page written as CSS selectors and as XPath, both run on the same day, and the two fields only XPath can find by their label.

Canonical: https://spider.cloud/learn/xpath-vs-css/

CSS selectors and XPath both pick elements out of an HTML page, and for most scraping fields either will do, since a tag, a class, an id or a position can be written in both. XPath can also choose an element by the words in it or next to it, which CSS cannot do, so a field you can only find by its label needs XPath.

The two come from different specifications, and they see the page differently. The W3C draft of Selectors Level 4 begins its abstract with "Selectors are patterns that match against elements in a tree". The XPath 1.0 Recommendation describes its own model this way: "XPath models an XML document as a tree of nodes." An element is one kind of node. A run of text is another, and XPath can test it.

Choosing fields is the step of [web scraping](/web-scraping/) where a fetched page becomes data, so the selector you write decides which change to the site's markup breaks your job.

## Five fields, one page

Books to Scrape is a sandbox shop built for scraping practice. The page used here sells A Light in the Attic, and a banner on it says the site is a demo. Each row below is one field, written once in each syntax, exactly as the run further down sent it. The last column marks the two fields whose rule can be written in only one of them.

| Field        | CSS                                          | XPath                                                                     | One syntax only     |
| ------------ | -------------------------------------------- | ------------------------------------------------------------------------- | ------------------- |
| Title        | `div.product_main > h1`                      | `.//div[@class="col-sm-6 product_main"]/h1`                               |                     |
| Price        | `div.product_main > p.price_color`           | `.//div[@class="col-sm-6 product_main"]/p[@class="price_color"]`          |                     |
| Availability | `div.product_main > p.availability`          | `.//div[@class="col-sm-6 product_main"]/p[@class="instock availability"]` |                     |
| UPC          | `table.table-striped > tr:first-child > td`  | `.//tr[th="UPC"]/td`                                                      | XPath, by its label |
| Reviews      | `table.table-striped > tr:nth-child(7) > td` | `.//tr[th="Number of reviews"]/td`                                        | XPath, by its label |

In the first three rows both columns walk the same steps. The `>` in CSS and the `/` in XPath both mean a direct child, and the `.//` that opens each XPath means any depth below the start of the search, which is where a CSS selector begins anyway.

They part ways on the class test. In CSS, `.product_main` matches any element that has `product_main` among its space-separated classes. In XPath, `@class="col-sm-6 product_main"` compares the whole attribute string. On this page the two land on the same div, but that agreement belongs to today's markup. If the shop adds a third class to that div, or swaps the order of the two it has, the CSS still matches and the XPath finds nothing. A full XPath 1.0 engine can test one class with `contains(concat(" ", normalize-space(@class), " "), " product_main ")`. The run below uses Python's ElementTree instead, and its documentation says of XPath that "The goal is to support a small subset of the abbreviated syntax; a full XPath engine is outside the scope of the module." That subset has no `contains()`, so the XPath column spells out the whole attribute.

The last two rows are where the languages split. In CSS, the UPC is the cell in the first row of the table and the review count is the cell in the seventh. That is a rule about position. The XPath finds the row whose header cell says UPC and takes the data cell in it. The XPath spec gives an example of the same test, a path that "selects the chapter children of the context node that have one or more title children with string-value equal to Introduction". The Python documentation describes its version of the predicate as one that "Selects all elements that have a child named tag whose complete text content, including descendants, equals the given text".

CSS has moved closer. Selectors Level 4 adds `:has()`, and the draft says it "represents an element if any of the relative selectors would match at least one element when anchored against this element." So `tr:has(th)` can pick a row by the elements inside it. It still cannot ask what the `th` says. No selector in the draft tests an element's text, and that gap is the whole difference in the last two rows. XPath can also walk up the tree, and its spec lists `..` as the step that "selects the parent of the context node".

This clip writes the same field in CSS and in XPath, then adds a row above it.

XPath or CSS: one field, both ways. 57 s, no sound. The words are on screen, and the captions button shows them at your own text size.

Read the transcript

XPath or CSS: one field, both ways. Five fields from one practice page, each written in both.

By class, both reach the same element and return the same text. Title. CSS: div.product_main > h1, by class. XPath: .//div\[@class="col-sm-6 product_main"]/h1, by class. Both returned A Light in the Attic. 5: fields written both ways. 5: returned the same value.

CSS counts to a row. XPath asks for the row whose header says UPC. UPC. CSS: table.table-striped > tr:first-child > td, by position. XPath: .//tr\[th="UPC"]/td, by its label. Both returned a897fe39b1053632. 2: of 5 fields XPath finds by a label. 1: the child CSS counts to.

Add a row above and child 7 is another row. The label still finds its own. A case, not the dated run: one row is added to the table's 7, as child 3. CSS still takes child 7, which is now another row. The XPath still finds the row whose header says Number of reviews, now child 8. 7: the child CSS still takes. 8: where the label is now.

Write CSS first. Use XPath when a label is all you have. Which one to write: the field is found by. class: Write CSS. It is shorter. label: Only XPath tests the words. position: Breaks when a row is added. This run: label.

Read the full page. The page is at spider.cloud/learn/xpath-vs-css.

## The run

The CSS column went to the API one selector at a time, in the `root_selector` field, with `return_format` set to text so that `content` holds only the text the selector matched. Below is the call for the UPC. The other four change only `root_selector`. Your key goes in `SPIDER_API_KEY`.

```bash
curl -s https://api.spider.cloud/scrape \
  -H "Authorization: Bearer $SPIDER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html", "request": "http", "return_format": "text", "root_selector": "table.table-striped > tr:first-child > td", "user_agent": "examplebot/1.0 (+https://example.com/bot; bot@example.com)"}'
```

The five calls ran between 00:57:21 and 00:57:30 UTC on 2026-11-21. Each one returned one page, at the address it was sent. The block gives that address once, then one line per call: the selector sent, the page status and the whole `content` field. The page count is how many pages the API sent back, not how many elements the selector matched. The API reports no match count for `root_selector`.

```text
url    https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html
pages  1 per call

div.product_main > h1                         200  A Light in the Attic
div.product_main > p.price_color              200  £51.77
div.product_main > p.availability             200  In stock (22 available)
table.table-striped > tr:first-child > td     200  a897fe39b1053632
table.table-striped > tr:nth-child(7) > td    200  0
```

The whitespace between the table's rows does not throw off that count. Selectors Level 4 says "Standalone text and other non-element nodes are not counted when calculating the position of an element in the list of children of its parent", But `:nth-child()` counts every element child, whatever its tag. `tr:nth-child(7)` means the seventh element child of the table, and only if that child is a `tr`. In the raw HTML of this page the table holds seven elements and every one is a `tr`, so the seventh child and the seventh row are the same element. A caption or a header group above the rows would shift the count by one.

The XPath column cannot go in the same field, since the API reference describes `root_selector` as a "CSS selector for the subtree to extract". It ran on the reader's side instead. The script below asks the API once for the page's raw HTML, builds a tree from it with Python's standard library, and runs the five expressions from the table as written. It needs nothing beyond Python 3. Save it as `xpath_fields.py` and run it with the key set.

```python
"""Fetch one practice page through the Spider API and run five XPath
expressions on it with Python's own ElementTree.

The small parser below is written for this one page, whose markup closes
every tag it opens. It does not follow HTML's rules for end tags a page
leaves out, so do not reuse it on other sites.

    python3 xpath_fields.py
"""
import json
import os
import sys
import urllib.request
import xml.etree.ElementTree as ET
from html.parser import HTMLParser

API = "https://api.spider.cloud/scrape"
URL = "https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html"
VOID = {"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "wbr"}

FIELDS = [
    ("title", './/div[@class="col-sm-6 product_main"]/h1'),
    ("price", './/div[@class="col-sm-6 product_main"]/p[@class="price_color"]'),
    ("availability", './/div[@class="col-sm-6 product_main"]/p[@class="instock availability"]'),
    ("upc", './/tr[th="UPC"]/td'),
    ("reviews", './/tr[th="Number of reviews"]/td'),
]


class Tree(HTMLParser):
    """Build an ElementTree from this page's HTML. Only void tags close themselves."""

    def __init__(self):
        super().__init__()
        self.root = ET.Element("document")
        self.stack = [self.root]

    def handle_starttag(self, tag, attrs):
        el = ET.SubElement(self.stack[-1], tag, {k: v or "" for k, v in attrs})
        if tag not in VOID:
            self.stack.append(el)

    def handle_endtag(self, tag):
        for i in range(len(self.stack) - 1, 0, -1):
            if self.stack[i].tag == tag:
                del self.stack[i:]
                return

    def handle_data(self, data):
        el = self.stack[-1]
        if len(el):
            el[-1].tail = (el[-1].tail or "") + data
        else:
            el.text = (el.text or "") + data


def main() -> int:
    key = os.environ.get("SPIDER_API_KEY")
    if not key:
        print("set SPIDER_API_KEY first")
        return 1
    body = json.dumps({
        "url": URL,
        "request": "http",
        "return_format": "raw",
        "user_agent": "examplebot/1.0 (+https://example.com/bot; bot@example.com)",
    }).encode()
    req = urllib.request.Request(API, data=body, headers={
        "Authorization": f"Bearer {key}",
        "Content-Type": "application/json",
    })
    with urllib.request.urlopen(req, timeout=60) as resp:
        page = json.load(resp)
    pages = page if isinstance(page, list) else [page]
    print("pages", len(pages))
    page = pages[0]
    print("url", page.get("url"))
    print("status", page.get("status"))

    tree = Tree()
    tree.feed(page.get("content") or "")
    for name, path in FIELDS:
        found = tree.root.findall(path)
        texts = [" ".join("".join(el.itertext()).split()) for el in found]
        print(f"{name:<13} {len(found)} match  {' | '.join(texts)}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
```

It ran at 01:11:47 UTC on 2026-11-21 under Python 3.14.7, and this is everything it printed.

```text
pages 1
url https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html
status 200
title         1 match  A Light in the Attic
price         1 match  £51.77
availability  1 match  In stock (22 available)
upc           1 match  a897fe39b1053632
reviews       1 match  0
```

Each expression matched exactly one element, and each value is the one its CSS partner returned about fifteen minutes earlier. The two columns agree on every field today. They disagree about which edits to the page would break them.

## Which one to write

Write CSS first. It is shorter for classes and ids, it tests one class without caring about the others, and the API's `root_selector` takes it. The [pagination page](/learn/pagination/) uses the same field to keep only a site's pager.

Reach for XPath when the field has a label and nothing else to hold on to, or when the text decides the match. A parent alone is not a reason. CSS can pick a parent by a child it can describe, so `tr:has(> th)` selects every row that has a header cell. What CSS cannot do is start from an element you already found by its text and step up from it. That is what `..` does in XPath, as in `.//th[.="UPC"]/..`, the row whose header says UPC. The two marked fields work in CSS today only because this table's rows come in a fixed order. If the shop adds a row above the review count, `tr:nth-child(7)` will return whatever moved into row 7, with a 200 status and nothing in the output to warn you. The label XPath keeps finding the review count for as long as the header says Number of reviews.

## Do this, avoid this

### Do this

- Write a field's rule from an id, a class or a label when the page has one, and use a row number only when it has none.
- Copy a class attribute from the raw HTML before an XPath compares it whole, and check it again when the site changes.
- Check that every field came back as one short value and one match, not a page of text.
- Select only the fields the job uses, and leave out personal data such as names and emails.

### Avoid this

- Picking a table cell by its row number when the row has a header you can test.
- Assuming a CSS class test and an XPath @class test will keep agreeing because they agree on today's page.
- Putting an XPath in a field the API reference documents as a CSS selector.
- Republishing long text you extracted, such as a product description, without checking who holds its copyright.

To try this on a page of your own, pick a field that has only a label and send its CSS row selector as `root_selector`. Do not point the script above at your page, because its parser only handles markup like this page's. Load the raw HTML into a parser that follows HTML's rules for end tags a page leaves out, such as `lxml.html`, and run the label XPath there. If both give the same value, keep the XPath. More pages on reading a site carefully are on the [learn index](/learn/).

## Sources

1. [W3C, Selectors Level 4, Working Draft of 22 January 2026](https://www.w3.org/TR/selectors-4/) Read November 20, 2026
2. [W3C, XML Path Language (XPath) Version 1.0, Recommendation of 16 November 1999](https://www.w3.org/TR/xpath-10/) Read November 20, 2026
3. [Python documentation, xml.etree.ElementTree, XPath support](https://docs.python.org/3/library/xml.etree.elementtree.html) Read November 20, 2026
4. [Spider OpenAPI file, the root_selector parameter](https://spider.cloud/openapi.yaml) Read November 20, 2026
