For most current Puppeteer code, use page.locator(selector) when you want to find an element and act on it. Use page.$() or page.$$() for immediate queries, and page.waitForSelector() when you need an explicit wait for an element to appear. Puppeteer recommends locators for selecting elements and interacting with them.
Choose a Puppeteer method for the job
| Goal | Method | What happens |
|---|---|---|
| Find an element and interact with it | page.locator(selector) |
Recommended interaction API. Locator actions wait for action preconditions and retry when the target is not ready. |
| Query the first match that exists now | page.$(selector) |
Returns an element handle or null if no match is found. |
| Query all matches that exist now | page.$$(selector) |
Returns an array of element handles, which may be empty. |
| Wait explicitly for a match or visibility | page.waitForSelector(selector, options) |
Waits for a selector state and returns an element handle or throws on timeout. |
| Read or transform one match | page.$eval(selector, fn) |
Runs a function on the first matching element; throws if there is no match. |
| Read or transform all matches | page.$$eval(selector, fn) |
Runs a function on the matching elements as a group. |
These methods and behaviors are documented in Puppeteer’s Page interactions guide and the waitForSelector API reference.
As an Amazon Associate I earn from qualifying purchases.
Pick a selector that identifies the element
CSS selectors work directly in Puppeteer selector APIs. Prefer a meaningful ID, name, data attribute, or other durable attribute when the page provides one. Avoid relying on generated class names or long absolute XPath expressions when a more readable selector is available.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitchesCSS selector
const submit = page.locator('button.submit');
await submit.click();
Text selector
Puppeteer supports text selectors. This example selects text matching “Save changes”:
#1 Best Overall
const save = page.locator('::-p-text(Save changes)');
await save.click();
Accessibility role and name
ARIA selectors use the browser’s computed accessible role and name:
const save = page.locator('::-p-aria([name="Save changes"][role="button"])');
await save.click();
XPath and shadow DOM
XPath selectors use the browser’s native Document.evaluate. Puppeteer also provides selector syntax for traversing open shadow roots; consult its selector guide for exact syntax and escaping rules, especially when selector text contains punctuation.
const submit = page.locator('::-p-xpath(//button[@type="submit"])');
await submit.click();
Find an element and interact with it using a locator
A locator describes how to find an element; actions such as click() and fill() perform the interaction. Locator actions check readiness conditions, including visibility and enabled state where relevant, viewport placement, and a stable bounding box for actions such as clicking or filling. This is useful when rendering or layout is still changing.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchPC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Rank #2
await page.locator('button.submit').click();
const email = page.locator('input[name="email"]');
await email.fill('[email protected]');
The locator action is usually preferable to querying an element handle and then acting on it when the page may still be changing. It does not guarantee that your selector is unique: ensure it describes the intended target.
Query elements that are already present
Get the first match
page.$() performs an immediate lookup. It does not wait for future rendering, so check for null before using the result.
const button = await page.$('button.submit');
if (button) {
await button.click();
await button.dispose();
}
Get every match
page.$$() returns all matches present at query time. The result can be empty.
const items = await page.$$('li');
for (const item of items) {
console.log(await item.evaluate(el => el.textContent?.trim()));
await item.dispose();
}
Read one element with $eval()
Use $eval() to run a function on the first matching element in the page context. It throws if the selector matches nothing.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
const value = await page.$eval(
'input[name="email"]',
el => el.value
);
In TypeScript, give the element a specific type when accessing element-specific properties such as an input’s value, for example HTMLInputElement.
Read or transform multiple matches with $$eval()
const labels = await page.$$eval(
'li',
items => items.map(item => item.textContent?.trim())
);
Wait for a dynamic element
Use page.waitForSelector() when you need to wait for a selector to enter the DOM or reach a requested visibility state. Its documented default timeout is 30,000 milliseconds; page default-timeout settings can change that. The method supports visible, hidden, timeout, and cancellation signal options.
Rank #4
const result = await page.waitForSelector('.result-card', {
visible: true,
timeout: 10_000,
});
if (result) {
await result.click();
await result.dispose();
}
waitForSelector() returns an element handle. Unlike a locator action, it does not automatically retry a later action if the element becomes unready after the wait. Dispose of the handle when you are finished with it. If your goal is simply to act on the element, prefer a locator and let its action handle readiness.
Read values or HTML in the page context
The function passed to $eval() or $$eval() runs in the page context. You can also pass an element handle to page.evaluate(); Puppeteer waits for a returned promise to resolve.
const heading = await page.$eval(
'h1',
element => element.textContent?.trim()
);
const body = await page.$('body');
if (body) {
const html = await page.evaluate(element => element.innerHTML, body);
await body.dispose();
}
Troubleshoot common lookup problems
- The query returns
nullor an empty array:$()and$$()only inspect the DOM at the time of the call. If content is rendered later, use a locator action or wait explicitly withwaitForSelector(). $eval()throws: no element matched when the query ran. Check the selector, or use$()and handlenullif absence is expected.- The wait times out: confirm the selector matches the actual DOM and that the requested state is possible. A wait for
visible: truewill not succeed merely because a matching node exists but is not visible. - The wrong matching element is used:
$()and$eval()operate on the first match. Make the selector more specific, or use$$()/$$eval()when you need to inspect all matches. - A handle is no longer needed: dispose element handles returned by
$(),$$(), orwaitForSelector()after use. - Text selector syntax fails: text and other custom selectors have Puppeteer-specific syntax and escaping rules. Check the current page interactions guide for selector punctuation and shadow-root details.
Or skip the browser setup
If your goal is to capture a page rather than automate a browser interaction, ScreenshotNeo can return a screenshot or PDF with one GET request. For example, with cURL:
Best Value
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
See the ScreenshotNeo API documentation for parameters. Before the shot, it accepts cookie/consent banners and removes 60+ known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks/CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers say which verdict applied and whether it was billed. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.
Sign up for 1,000 free screenshots a month, with no card required.
Frequently Asked Questions
Does Puppeteer’s $() wait for an element to appear?
No. It checks for a match at the time it runs and returns null when there is none.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →What does Puppeteer’s waitForSelector() return?
It returns an element handle when the selector reaches the requested condition; it throws if the wait times out.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




