Web scraping
How do I locate elements with CSS selectors in Puppeteer?
Pass a CSS selector to page.$ for one element, page.$$ for all of them, or page.$$eval to read values straight out of the page in a single call.
The quick answer
Puppeteer accepts standard CSS selectors almost everywhere. page.$(sel) returns the first matching element handle or null, page.$$(sel) returns an array, and page.$eval or page.$$eval run a function inside the page on the matches and send back plain values. For clicking and typing, page.locator(sel) waits for the element to be ready before acting.
Reading data in one round trip
Element handles are references to objects that live in the browser. Every property you read through them is another message across the DevTools connection. For extraction, push the work into the page with $$eval and return a ready array:
import puppeteer from "puppeteer"; // bundles a matching Chrome
const chrome = await puppeteer.launch({ headless: true });
const bookTab = await chrome.newPage();
await bookTab.goto("https://books.example.org/new-releases", { waitUntil: "domcontentloaded" });
await bookTab.waitForSelector("article.book");
const books = await bookTab.$$eval("article.book", (nodes) =>
nodes.map((n) => ({
title: n.querySelector("h2")?.textContent.trim() ?? null,
author: n.querySelector(".byline a")?.textContent.trim() ?? null,
link: n.querySelector("a.cover")?.href ?? null,
}))
);
console.log(books.length, books[0]);
await chrome.close();
Inside the callback you are in the browser, so querySelector, textContent and the resolved href property all work as in DevTools. Only serializable values come back: strings, numbers, arrays and plain objects.
Puppeteer additions to CSS
Recent Puppeteer versions extend selector strings with prefixed pseudo elements. At the time of writing these include ::-p-text(Sign in) for matching visible text, ::-p-aria(Submit order) for the accessible name, and ::-p-xpath(...) for an XPath expression. They also pierce open shadow roots with >>>. Check the selector documentation for the version you run, since this area has changed between releases.
await bookTab.locator("button::-p-text(Load more)").click();
const priceBadge = await bookTab.$("product-card >>> span.badge");
Choosing selectors that survive
- Prefer stable hooks: ids,
data-*attributes, formnamevalues and ARIA labels. - Avoid generated class names such as
css-1x9kq2, which change on every site build. - Avoid long chains copied from DevTools (
div > div:nth-child(3) > span); one layout tweak breaks them. - Scope inside a container: first find the card, then query within it, so fields cannot leak between cards.
Waiting before selecting
A selector that is correct can still return null because the element has not rendered yet. Call waitForSelector first or use locators, which wait on their own. The page on waiting for a page to load in Puppeteer lists the options. When nothing ever appears, take a screenshot: a challenge page or CAPTCHA is a common reason, and the Puppeteer integration shows how to solve one and carry on.
Common errors
Error: failed to find element matching selectorfrom$eval: unlike$, it throws when nothing matches. Wrap it or check with$first.- Selectors inside iframes: query the frame object from
page.frames(), not the page. - Escaping: ids that start with a digit or contain colons need escaping in CSS, for example
#\31 23; an attribute selector such as[id="123"]is simpler.
Handles, locators or evaluate?
Each tool has a natural job. Use $$eval or page.evaluate when you want data out of the page: one call, plain values back, nothing to clean up. Use locators when you want to act on the page, because they retry until the element is visible, enabled and stable, which removes most flaky clicks. Keep element handles for the rare cases where you need to pass a node between several steps, such as uploading a file to an input, and dispose of them when you are done in long sessions so they do not pile up in browser memory.
A useful habit while building a scraper is to test every selector in the DevTools console first with document.querySelectorAll("...") and check the count. If the console shows 24 matches and your script returns zero, the difference is timing or the document your script loaded, not the selector. If both show zero, the selector is wrong. That one comparison settles most "selector does not work" questions in under a minute, and it works the same way for Playwright and plain browser scripts.
Common questions
What is the difference between page.$ and page.locator?
page.$ returns a handle immediately or null; a locator waits for the element to be ready when you act on it.
Can I select by text with plain CSS?
No, CSS has no text matching. Use Puppeteer's ::-p-text pseudo selector or an XPath expression.
Why does $eval throw instead of returning null?
It requires a match to run the callback. Use page.$ if the element is optional.
How do I read an attribute value?
Inside $eval call el.getAttribute("name"), or read the property such as el.href for the resolved URL.
Do CSS selectors work inside iframes?
Yes, but you must run them on the frame object, found through page.frames() or an element handle's contentFrame().
Keep reading
- PuppeteerThe Node.js library that drives Chrome and Chromium over the DevTools Protocol, popular for scraping, screenshots and PDFs.
- CSS selectorCSS selectors are the compact pattern language for picking elements by tag, class, attribute and position, and most scraping tools speak it.
- Web scraping with PuppeteerPuppeteer scraping beyond the basics: picking the right navigation wait, bulk extraction with $$eval, blocking heavy requests and capturing JSON.
- PuppeteerOne Puppeteer client for three jobs: the reCAPTCHA v2 checkbox, v3 scores tied to an action, and text image CAPTCHAs.