Glossary
CSS selector: picking elements by pattern
A CSS selector is a short pattern that matches elements in an HTML document, originally for styling and now the most common way scrapers locate data.
Definition
Selectors were designed so stylesheets could say which elements a rule applies to. The same syntax works anywhere you need to find elements: document.querySelectorAll in the browser, Playwright and Puppeteer locators, Beautiful Soup's select, Cheerio, lxml's cssselect and Scrapy's response.css.
Syntax you will use most
| Selector | Matches |
|---|---|
article | Every article element |
.price | Elements with class price |
#main | The element with id main |
div.card h2 | h2 anywhere inside a div.card (descendant) |
ul > li | li that are direct children of a ul |
h3 + p | The p right after an h3 |
[data-sku] | Elements with a data-sku attribute |
a[href^="/product/"] | Links whose href starts with a prefix |
img[src$=".webp"] | Images whose src ends with a suffix |
li:nth-child(2) | The second child, if it is an li |
div:not(.ad) | Divs without class ad |
section:has(h2) | Sections containing an h2 (support varies by library) |
Writing selectors that last
A selector copied from the browser's "Copy selector" menu often looks like #app > div:nth-child(3) > div > div:nth-child(2) > span. It works today and breaks the next time a wrapper div is added. Prefer anchors that carry meaning:
- Data attributes such as
[data-testid="price"]or[itemprop="price"], which developers keep stable for tests and SEO. - Semantic classes like
.product-titleover generated ones like.css-1x9f2k, which change on every build. - Short paths: a stable container plus the target, nothing in between.
- Scoped lookups: select each card first, then query fields inside it, so fields from different cards never mix.
Example in Scrapy
def parse(self, response):
for card in response.css("div.listing[data-id]"):
yield {
"id": card.attrib["data-id"],
"title": card.css("h2.listing-title::text").get(default="").strip(),
"price": card.css("[itemprop=price]::attr(content)").get(),
}
The ::text and ::attr() pseudo elements are Scrapy extensions, not standard CSS. Other libraries read text and attributes with method calls instead.
Testing selectors before you ship
Try every selector in the browser console with document.querySelectorAll() on two or three different pages of the same type, not just the one you built it on. Product pages without a discount, listings with a single result and out of stock items are where fragile selectors usually fail. Save those pages as fixtures and run your extractor against them in tests.
Limits and alternatives
CSS cannot select by text content or move up to a parent in most libraries. When you need "the cell next to the label that says Price", XPath is often simpler.
Selectors for CAPTCHA widgets
Detecting a challenge is a selector job too. .g-recaptcha[data-sitekey] finds a reCAPTCHA v2 widget and its key, .cf-turnstile[data-sitekey] a Cloudflare Turnstile widget, and textarea[name="g-recaptcha-response"] the field where a solved token goes. Run these checks before your data selectors, so a challenge page is handled rather than parsed as empty data.
Common questions
Are CSS selectors faster than XPath?
In most libraries the difference is small. Choose by readability and by what you need to express, not by speed.
Why did my copied selector stop working?
Browser generated selectors depend on exact nesting and position, so any layout change breaks them. Use stable attributes instead.
Can a CSS selector match text content?
Standard CSS cannot. Some libraries add pseudo classes for it, or you can use XPath, which supports text matching.
What does the > symbol mean in a selector?
It matches only direct children, while a space matches descendants at any depth.
How do I detect a reCAPTCHA widget with a selector?
Look for an element matching .g-recaptcha with a data-sitekey attribute, then read the key from that attribute.
Keep reading
- XPathXPath navigates a document tree in any direction, matches on text, and handles cases where CSS selectors run out of road.
- 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 find elements by class in Beautiful Soup?Use find_all with class_, or select with a dot selector; both match one class among several on the same tag.
- How do I locate elements with CSS selectors in Puppeteer?Puppeteer takes CSS selectors in page.$, page.$$, the $eval helpers and locators, plus its own pseudo selectors for text.