Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

For new Puppeteer interactions, start with page.locator(). Locators wait for an element to exist and become actionable before clicking, filling, hovering, or scrolling. Use $, $$, $eval, or $$eval when you need an immediate query against a page that is already ready, and use waitForSelector() when you specifically need a lower-level wait or an element handle.

This guide reflects the official Puppeteer documentation checked on September 29, 2026 (version 25.12.0 pages; the $$eval reference reported 25.9.0). Confirm the live API reference when upgrading because method details can change.

Set up Puppeteer and open a page

Install Puppeteer in a Node.js project, then launch a browser and navigate to a URL:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
npm install puppeteer
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com', {waitUntil: 'domcontentloaded'});

  // Locate and use elements here.

  await browser.close();
})();

Always close the browser in a finally block in production code so a navigation or selector error does not leave Chromium processes running.

#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents

Use locators for interactions

The interactions guide recommends locators as the default way to select and interact with elements. A locator records how to find the target and, before acting, waits for presence, visibility and readiness. For a click, Puppeteer also checks that the element is in the viewport, enabled, and has a stable bounding box across two animation frames.

Click a button

await page.locator('button[type="submit"]').click();

Fill an input

await page.locator('input[name="email"]').fill('[email protected]');

Other locator actions include hover(), scroll(), and wait(). Locator APIs also support filtering, mapping, locator functions, and a per-locator timeout. Prefer a selector that expresses the element’s role or stable identity rather than a long chain of layout classes.

CSS selectors and Puppeteer selector syntax

CSS is the default syntax, so ordinary selectors such as #login, .product-card, and button[data-testid="save"] work directly. Puppeteer also adds selector forms for text, XPath, accessibility role/name, and queries that cross open shadow roots.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Find by visible text

await page.locator('div ::-p-text(Checkout)').click();

The text selector chooses minimal, deepest matching elements, including matches inside open shadow roots. Special characters used by the selector syntax, including parentheses, must be escaped when they occur in the text pattern.

Find with XPath

const heading = await page.waitForSelector('::-p-xpath(//h2)');

The ::-p-xpath() form keeps XPath explicit while using Puppeteer’s selector engine.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors

Use accessibility role and name

For controls whose accessible semantics are reliable, use Puppeteer’s role/name selector syntax documented in the Page locator reference. This can be more resilient than styling classes because it follows the control’s user-facing role and accessible name. Check the current reference for the exact role selector grammar when you adopt it in a project.

Cross open shadow roots

Puppeteer’s extended selectors can traverse open shadow roots. Closed shadow roots remain inaccessible to page JavaScript, so expose an application-level test hook or query the host element instead of trying to pierce them.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose an immediate query method

These methods query the DOM immediately; they do not wait for a future match.

Need Method Result Important behavior
First current match page.$(selector) Element handle or null Returns only the first match.
All current matches page.$$(selector) Array of handles or [] Returns every current match.
Read one match in page context page.$eval(selector, fn) Serializable value from fn Throws if no element matches.
Read all matches in page context page.$$eval(selector, fn) Serializable value from fn Passes the matching element array to fn.

Read one element

const first = await page.$('.item');
if (first) {
  const text = await first.evaluate(el => el.textContent);
  console.log(text);
}

Extract a value with $eval

const value = await page.$eval('input[name="q"]', el => el.value);

The callback runs in the page context. Return a serializable value such as text, an input value, a URL, or outerHTML; do not return a live DOM node.

Extract a list with $$eval

const labels = await page.$$eval('.item', els =>
  els.map(el => el.textContent?.trim() ?? '')
);

Use $$eval when you want one page-context operation over all matches, rather than creating and managing a handle for each item.

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

Wait for a dynamic element with waitForSelector

waitForSelector() is a lower-level wait. It resolves immediately if the selector already matches, or waits until the timeout expires. Its documented default timeout is 30,000 milliseconds.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Wait for visibility

const element = await page.waitForSelector('.result', {
  visible: true,
  timeout: 10000
});
// Use the handle here.
await element.dispose();

visible: true requires a visible DOM element. Without a match before the timeout, Puppeteer throws. Dispose element handles when finished, especially in loops or long-running workers.

Wait for hidden or absent content

await page.waitForSelector('.loading', {hidden: true});

With hidden: true, Puppeteer waits for the element to be hidden or absent. If it is not found, the result may be null.

Why a locator is usually safer for actions

A handle returned by waitForSelector() is a snapshot of an element. If a framework replaces that node after the wait, a later action can fail. The lower-level API also does not automatically retry the action. A locator retains the selection strategy and is therefore the better starting point for click or fill operations on dynamic interfaces.

A practical decision framework

  • Find and interact: use page.locator(selector).
  • Read one element that should already exist: use page.$() or $eval().
  • Read a collection: use page.$$() or $$eval().
  • Wait for presence, visibility, or disappearance and keep a handle: use waitForSelector().

An immediate query and a wait are different operations. Do not add a fixed delay merely to compensate for choosing the wrong one; wait for a selector, navigation state, or another observable condition.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

Reliable selector patterns

Prefer stable contracts

  • Use a dedicated data-testid or similarly stable attribute when your team controls the markup.
  • Use accessible role and name for user-facing controls when the accessibility tree is maintained.
  • Use text selectors for content whose wording is part of the intended contract.
  • Avoid generated class names, positional selectors such as :nth-child(), and selectors tied only to visual layout.

Handle repeated and changing content

For a list, query the container and map its children, or use $$eval. If a result is rendered after an action, perform the action with a locator and then wait for the result locator rather than sleeping for an arbitrary duration.

Frames and shadow DOM

An element inside an iframe belongs to that frame’s document. Locate the frame, obtain its frame context, and query there; a selector on the top-level page cannot match inside it. Open shadow roots can be crossed with Puppeteer’s extended selectors, while closed roots cannot.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting selector failures

“No element found” or a timeout

  • Verify the URL and navigation completion state.
  • Check whether the element is inside an iframe or shadow root.
  • Confirm the selector in DevTools and account for case, whitespace, and escaping.
  • Increase the timeout only after fixing a race or genuinely slow page; do not hide a permanently incorrect selector with a longer wait.

The element exists but click fails

  • Use a locator so Puppeteer can wait for visibility, enabled state, viewport position, and layout stability.
  • Check for an overlay, cookie dialog, or animation covering the target.
  • Wait for the application state that enables the control rather than forcing a click.

$eval throws while $ returns null

This is expected: $eval requires at least one match. Use $ for an optional element, or wait before calling $eval.

A handle becomes detached

The page replaced the node. Re-query or use a locator, which can resolve the current node when the action is performed. Dispose stale handles.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Text or XPath syntax errors

Escape selector-special characters in text patterns and keep XPath inside ::-p-xpath(...). If a selector is difficult to review, split the operation into a stable container query and a simpler descendant query.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

Performance, reliability, and timeout notes

Queries run in the page and should be cheap compared with navigation or rendering, but repeatedly scanning a large DOM is avoidable. Narrow selectors, extract a collection in one $$eval, and avoid creating thousands of handles when a serializable array is enough. Set timeouts according to the page’s known behavior, and use cancellation or cleanup in workers that process many pages. A successful selector still depends on the page being loaded, the correct frame being selected, and the application not replacing the node between operations.

Or skip the browser setup

If your goal is a clean image or PDF rather than DOM-level automation, ScreenshotNeo provides a website screenshot API and MCP server. One GET request captures a URL as PNG, JPEG, WebP, or PDF; it handles the browser setup for you.

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 documentation for all options. Cookie and consent banners, newsletter popups, and chat widgets are removed before the shot. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server includes take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frequently Asked Questions

Can Puppeteer select an element by its accessible name?

Yes. Puppeteer’s locator selector support includes accessibility role/name queries; use the current Page locator reference for the exact selector grammar.

When should I use waitForSelector instead of a locator?

Use waitForSelector when you specifically need a lower-level wait or an element handle, including visibility or hidden-state checks. Use a locator for most interactions because it retains the selection strategy and readiness checks.

What does Puppeteer return when a selector has no matches?

page.$() returns null, page.$$() returns an empty array, and $eval throws. waitForSelector throws after its timeout unless the hidden condition is satisfied.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.