XPath vs CSS selector for scraping, and where regex fits

All three answer the same question: where on this page is my value? They differ in what they can point at, how fast they run, and how they fail when the site changes. "Never parse HTML with regex" is good advice for writing one by hand. It doesn't hold for reading one value from a kind of page you know.

XPath, CSS selectors and regex

CSS    div.product > span.price
XPath  //div[@class="product"]//span[contains(text(), "€")]
Regex  <span class="price">\s*€\s*([\d.,]+)

Nederlands

What each one can do

Can it…CSS selectorXPathRegex
Pick by tag, class or idyesyesyes, as text
Pick by the text insidenoyesyes
Walk up to a parentonly with :has()yesno
Read part of a value, like 8,99 from "€ 8,99 incl."nobarelyyes
Read JSON inside a script tagnonoyes
Work without parsing the page firstnonoyes

Which is faster?

A regular expression reads the raw text and stops at the first match, with no tree to build. CSS and XPath need the whole page parsed first, and that is where most of the time goes. On a few hundred pages you won't notice. On millions, parsing is the bill.

Why hand-written selectors and regexes break

  1. Written on one page. It fits the example. Only more pages show which part of it was luck.

  2. Tied to class names. div.css-1x2y3z is gone after the next release. The words near the value ("Price", "In stock") usually stay.

  3. Tied to a position. The third span, the second table row: one extra badge and you read the neighbour.

  4. Silent. A selector that matches nothing returns nothing. One that matches the wrong thing returns a value, and nobody notices.

Which should you use?

  1. CSS selector. The default when you write by hand: short and easy to read.

  2. XPath. When you need the text inside an element, or its parent.

  3. Regex. For a piece of a value, JSON in a script tag, or speed. Hard to write well by hand, easy for a machine to grow from examples and test.

Regex rules, grown from examples

That last point is what this site does. From a few example pages it grows a regular expression per field until it fits every one, adds backups, and tells you per value whether the main rule matched. You get the speed of regex without writing one.

More on this

Tested on 207 real pages from 49 sites: 609 of 659 values exactly right, 0 wrong. The rest came back as not found, unsure or in another format.

Made by Simon. I have been scraping for more than five years and building software since 2015.

Try it on your own pages

Paste a few links and a couple of values. The look is free, and you hear the price before anything is due.

Try it on your pages

The first look is free, and you hear the price before anything is due. If I can't get your examples right, you don't pay.