ApiSkills

Web Scraping · 9 min

CSS selectors for extraction

The handful of selector patterns that let you pull almost any field — and how to write ones that survive a redesign.

A CSS selector is a pattern that picks elements out of a page. The same selectors that style a page can extract from it. Learn this handful and you can pull almost any field.

SelectorMatches
p, aEvery element of that tag
.priceEvery element with that class
#featuredThe one element with that id
.card.saleElements with BOTH classes (no space = AND)
.card .priceA .price anywhere inside a .card (space = descendant)
.card > .titleA .title that is a DIRECT child of .card
h4 + pThe p immediately after an h4 (adjacent sibling)
[href^="/x"]Attribute starts-with (^= starts, $= ends, *= contains)
tr:nth-child(even)By position among siblings
.plan:not(.featured)Everything matching, except a case you exclude

The biggest beginner mistake is the space. .card.sale means ONE element carrying both classes; .card .sale means a .sale somewhere inside a .card. They behave completely differently.

Write selectors that survive a redesign

  • Prefer stable class or data-* names over positional chains: .product-card .price survives edits that break .list > div:nth-child(2) > span.
  • Avoid the browser "Copy selector" — it generates brittle, positional paths tied to the exact current layout.
  • A selector is only as stable as the HTML behind it; when a site is redesigned, expect to update it. That is the main maintenance cost of scraping.

Tip · Do not just read this — the Scraping Lab at /scraping has 12 interactive challenges where you type a selector and see exactly what it matches (green = right, red = wrong), plus a 26-question quiz.