Glossary
CSS selectors
CSS selectors are patterns that match elements in an HTML document by tag, class, ID, attribute or position, and in web scraping they are the most common way to tell a parser which elements hold the data you want.
CSS selectors are patterns that match elements in an HTML document by tag, class, ID, attribute or position. They were designed so stylesheets could say which elements a rule applies to, and the same syntax is now the standard way for scrapers, test scripts and browser agents to point at the parts of a page they need.
In web scraping, a selector is the bridge between a page and a record. A rule such as “div.product h2” says “every h2 inside a div with the class product”, and running it against the DOM returns those elements so their text or attributes can be read. Nearly every scraping library supports CSS selectors, which makes them the first tool most developers reach for.
The selector syntax that matters for scraping
Most scraping needs a small part of the full CSS selector language. The table covers the forms you will use most often.
Selector | Matches | Example |
|---|---|---|
Type | Every element with a tag name | h2 or table |
Class | Elements with a class | .price |
ID | The element with an ID | #main-content |
Attribute | Elements with an attribute, or a specific value | a[href] or [data-sku=”A123”] |
Attribute substring | Attribute values that start with, end with or contain text | a[href^=”https”] or img[src$=”.png”] |
Descendant | Elements anywhere inside another | article p |
Child | Direct children only | ul > li |
Sibling | Elements that follow another at the same level | h3 + p or h3 ~ p |
Position | Elements by their place among siblings | tr:nth-child(2) or li:first-child |
Negation | Elements that do not match a pattern | li:not(.ad) |
Relational | Elements that contain a match | div:has(> img) |
Selectors combine freely. “table.results tr:not(:first-child) td:nth-child(3)” reads as the third cell of every row except the header row in the results table. Long chains like that work, but each extra step is another assumption about the page that a redesign can break.
A worked example
Imagine a job board where each listing looks like this in the rendered page: an article element with the class job, containing an h3 with the job title, a span with the class company, a span with the class location, and a link whose href points to the full advert. Some listings also carry a span with the class salary.
A scraper uses one selector to find the containers and then short selectors inside each one. It selects “article.job” to get every listing, then within each listing reads “h3” for the title, “.company” and “.location” for the next two fields, “a[href]” for the link, and “.salary” if it exists. Scoping the inner selectors to the container matters: selecting “.company” on the whole page would return every company name in one list, with no way to tell which belongs to which job once one listing lacks a field. If the site later wraps each listing in an extra div, the scoped selectors still work, because they only depend on the article.job container and the elements inside it.
The output is a list of records with title, company, location, salary and URL. From there it goes through the usual data normalisation steps: trimming whitespace, resolving relative links and turning salary text into numbers where possible.
Where you use CSS selectors
In the browser, document.querySelector returns the first match and querySelectorAll returns every match. Browser automation libraries such as Playwright, Puppeteer and Selenium accept CSS selectors for finding elements to read or click, and many test frameworks build their locators on top of them.
Outside the browser, parsing libraries apply the same syntax to raw HTML. Python’s Beautiful Soup has a select method, Node’s Cheerio uses a jQuery-style API, and most languages have a fast parser with selector support. These work on the page source, so they only see content present in the HTML the server returned. For pages that build content with scripts, the selector has to run against the rendered DOM in a headless browser, as described under JavaScript rendering. HTML parsing covers the parser choices in more depth.
Scraping frameworks and no-code tools also accept selectors in configuration, so a non-developer can point a field at “.price” without writing code. AI tools increasingly generate selectors too: a model looks at a sample of the page and proposes a selector for each field, and the scraper then runs those selectors cheaply on thousands of pages.
Selectors for tables, lists and pagination
Tables are a common target and have their own patterns. “table#rates tbody tr” returns the data rows, and “td:nth-child(n)” picks a column by position. Position-based selection is fragile when columns are added, so a more robust approach reads the header row first, builds a map from header text to column index, and then reads cells by that index. Lists of links, such as search results or category pages, usually come down to one container selector plus “a[href]” inside it.
Pagination is another selector job. A scraper finds the next-page link with a selector such as “a[rel=next]” or “nav.pagination a:last-child”, follows it, and repeats until the link disappears. Infinite scroll is harder: there is no link to select, so the scraper either scrolls an automated browser and waits for new items, or finds the API request the page makes and calls it directly.
CSS selectors vs XPath
XPath is the other common way to address elements, and each has strengths.
Need | CSS selectors | XPath |
|---|---|---|
Match by tag, class, ID or attribute | Yes, short syntax | Yes, longer syntax |
Match by visible text | No standard way | Yes, with contains() or text() |
Move up to a parent or ancestor | Limited, with :has() | Yes, with parent and ancestor axes |
Readability for web developers | High | Lower |
Support in browsers and scraping libraries | Universal | Common, slightly less universal |
A sensible default is to write CSS selectors and switch to XPath for the cases CSS handles badly, such as “the price cell in the row whose first cell says Total”. Many tools accept both, and mixing them in one scraper is normal.
Writing selectors that last
Selectors break when sites change, and some break much more often than others. A few habits reduce the maintenance load.
Prefer stable hooks. IDs, data attributes such as data-testid or data-sku, and semantic tags such as article, nav and table usually survive redesigns. Class names generated by build tools, which look like “css-1x2y3z”, change on every deploy and should be avoided.
Keep chains short. “main .product .price” is easier to maintain than a seven-step path copied from the browser’s developer tools. Copied paths encode every wrapper div on the way down, and one extra wrapper breaks them.
Scope to a container. Select the repeating unit first, then use short selectors inside it, as in the job board example. This keeps fields aligned and makes missing values obvious.
Validate the output. Check that every record has the required fields, that prices parse as numbers, and that counts look plausible. A selector that suddenly returns nothing, or ten times as many matches as yesterday, is the clearest sign a page has changed.
Monitor in production. Run each selector against a saved copy of the page in tests, and against the live page on a schedule, and alert when match counts change sharply. Keep selectors in version control and note when each one was last confirmed against the site.
Use structured data when it exists. Many pages embed schema.org JSON-LD or Open Graph tags with the same facts in a machine-readable form, and reading those is more robust than selecting visible text. Meta tags are also selectable with plain attribute selectors such as meta[property=”og:title”].
When selectors are the wrong tool
Selectors assume you know the page’s structure in advance. When you scrape thousands of different sites, writing selectors per site does not scale. In that case the usual approach is generic extraction: boilerplate removal or reader mode to find the main content, conversion with HTML to Markdown, and then structured data extraction with a model that fills a schema from the text. This costs more per page than running a selector, but it needs no per-site maintenance, and the output is LLM-ready data.
Selectors also say nothing about whether you should scrape a page. Check robots.txt, the site’s terms and the guidance under is web scraping legal before running a scraper at scale, and prefer an official API where one exists, as web scraping vs API explains.
Where Exabase fits
Exabase does not run custom CSS selectors against pages. It covers the generic path, where you want the content of a page without maintaining selectors for each site.
Exabase Extract renders a URL with JavaScript and returns its title, site name and content as text chunks, and the same endpoint processes PDFs, images, audio and video. The extraction guide explains polling and webhooks, and the website to JSON and web scraper tools show the output for a single URL. The file extraction page covers how one endpoint replaces a parser per format.
Once content is stored as Resources, Deep Search finds the passage that answers a question at the sub-document level, so an agent does not need a selector to locate a fact in a saved page. Teams comparing scraping services can start with the best web scraping API roundup and Firecrawl alternatives.
Frequently asked questions
What is a CSS selector in web scraping?
A CSS selector is a pattern that tells a scraper which elements on a page to read, such as “.price” for elements with the class price. The scraper runs it against the page’s HTML or DOM and extracts the text or attributes of the matches.
How do I find the CSS selector for an element?
Open the browser’s developer tools, inspect the element and look for a stable ID, data attribute or short class combination. The “copy selector” option works, but it usually produces long, fragile paths that are worth shortening by hand.
Are CSS selectors faster than XPath?
For most scraping work the difference is negligible. Choose by readability and by what you need to express, and use XPath when you must match on text or move up the tree.
Why does my CSS selector return nothing?
The content is often added by JavaScript after the page loads, so it is not in the HTML your parser received. Other causes are a class name that changed, an element inside an iframe or shadow DOM, or a typo in the selector.
Can CSS selectors select by text?
Standard CSS selectors cannot match on visible text. Some tools add their own text selectors, and XPath can do it with contains().
Can an LLM write CSS selectors for me?
Yes. A model can propose selectors from a sample of the page, and running those selectors at scale is much cheaper than sending every page to the model; validate the output, because proposed selectors can be wrong.
Do I need CSS selectors to use Exabase?
No. Exabase Extract returns a page’s content as text chunks without per-site selectors, and Deep Search finds passages within stored pages.
Related pages: XPath, DOM, HTML parsing, Web scraping, Browser automation, Structured data extraction, Boilerplate removal, Best web scraping API, File extraction