To find an element in Puppeteer, pass an ordinary CSS selector to a locator or query method. For interactions, start with page.locator(selector); it waits for the element and checks that the requested action is ready. Use page.$() to retrieve the first match, page.$$() for every match, and page.waitForSelector() when you need an explicit wait. The examples below show how to choose among them, handle missing matches, and reach beyond CSS when necessary.
Choose the Puppeteer API for the job
Puppeteer accepts CSS selectors by default across its selector APIs. A selector such as button.primary, #account-menu, or [data-testid="ready"] can be passed directly; you do not need a special CSS prefix. The best API depends on whether you want to act on an element, retrieve an element handle, collect several matches, or wait explicitly for an element to appear. See the Puppeteer Page interactions guide.
| Need | Use | Result and waiting |
|---|---|---|
| Interact with a matching element | page.locator(css) |
Returns a locator; action methods wait for readiness and retry when their conditions are not met. |
| Retrieve just the first matching element | page.$(css) |
Returns an ElementHandle or null if there is no match. |
| Retrieve every matching element | page.$$(css) |
Returns an array of ElementHandle objects, or an empty array if there are no matches. |
| Read data from the first or all matches | page.$eval(css, fn) or page.$$eval(css, fn) |
Runs a function in the page with the first matched element or an array of all matched elements. |
| Wait for an element to appear or become visible | page.waitForSelector(css, options) |
Waits explicitly and returns an element handle when the condition is met; a timeout throws. |
These are not interchangeable merely because each can take the same selector. A locator is oriented toward actions; query methods give you handles or values to process; an explicit wait makes the point at which your script pauses visible in your code.
Use a locator when you want to interact
For a click or form entry, use a locator with the CSS selector and the relevant action. Locator actions automatically wait for the element and for action conditions rather than requiring a separate query followed by a manual readiness check.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstall#1 Best Overall
- FULL HD IPS DISPLAY - Enjoy vibrant, crystal-clear images with 178-degree wide-viewing angles
- AMD RYZEN 3 30 PROCESSOR - Everyday performance you can count on; Multitask, stream, game casually, and edit photos smoothly with responsive power and vibrant HDR visuals
- ENJOY UP TO 14 HOURS AND 15 MINUTES OF BATTERY LIFE - HP Fast Charge restores battery from 0 to 50% in approximately 45 minutes
- AMD RADEON 610M GRAPHICS - Experience smooth entertainment; Built for streaming and multitasking, enjoy realistic visuals and efficient performance for work and play
- STORAGE AND MEMORY - 512 GB PCIe NVMe M.2 SSD offers fast speed and efficient storage; and 8 GB LPDDR5 RAM memory boosts performance with higher bandwidth
await page.locator('button.primary').click();
await page.locator('input[name="email"]').fill('[email protected]');
await page.locator('#account-menu button.save').click();
For a click, Puppeteer documents readiness checks that include the element being in the viewport, visible, enabled, and having a stable bounding box across two animation frames. If those conditions are not met, the locator retries the action rather than treating an early match as proof that a click can succeed. This makes locators a useful default for interaction with content that may still be rendering or changing. See Page.locator() and the interaction guide.
A locator does not mean that any selector is a good selector. Prefer a selector that identifies the intended control, such as a stable ID, meaningful class, or attribute, instead of a long chain tied to incidental page structure. For example, input[name="email"] conveys more intent than a selector that depends on several nested layout containers. CSS is well suited to tags, classes, IDs, attributes, and structural relationships.
Retrieve one match, all matches, or values
First match: page.$()
Use page.$() when your next step needs an element handle and only the first matching element matters.
const button = await page.$('button.primary');
if (button === null) {
throw new Error('No primary button was found');
}
// Use the ElementHandle as needed.
await button.click();
await button.dispose();
If no element matches, page.$() resolves to null; it does not guarantee a result or wait for a future match. Check for null before using the handle. Dispose of an element handle when you are finished with it to avoid keeping unnecessary handles alive. Details are in the Page.$() API reference.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteEvery match: page.$$()
Use page.$$() when you need a collection of element handles. It returns all current matches, and returns [] when none exist.
Rank #2
- Intel Celeron N4120: 4 Cores & Threads, 1.1GHz Base Clock, Up to 2.6GHz Boost Clock, 4MB Cache, Intel UHD Graphics 600. The perfect combination of performance, power consumption, and value helps your device handle multitasking smoothly and reliably with four processing cores to divide up the work.
- 14" HD Display: 14.0-inch diagonal, HD (1366 x 768), micro-edge, anti-glare. See your digital world in a whole new way. Enjoy movies and photos with the great image quality and high-definition detail of 1 million pixels.
- Memory & Storage: 4 GB LPDDR4x & 64 GB eMMC Storage. Adequate high-bandwidth RAM to smoothly run multiple applications and browser tabs all at once. An embedded multimedia card provides reliable flash-based storage.
- Ports:2 x USB 3.0 Type-A,1 x USB 3.0 Type-C,1 x HDMI,1 x Headphone Jack
- Chrome OS: Chromebook is a computer for the way the modern world works, with thousands of apps. Enjoy the seamless simplicity that comes with Google Chrome and Android apps, all integrated into one laptop. It’s fast, simple, and secure.
const buttons = await page.$$('button.primary');
if (buttons.length === 0) {
console.log('No primary buttons were found');
} else {
for (const button of buttons) {
// Inspect or interact with each handle as appropriate.
await button.dispose();
}
}
The empty array is a normal result, so branch on its length if the script requires at least one match. Dispose of handles when they are no longer needed. See the Page.$$() API reference.
Read values with $eval() and $$eval()
When your goal is to read data rather than keep element handles, use the evaluation helpers. $eval() passes the first matching element to a function; $$eval() passes an array containing all matches.
const headingText = await page.$eval('h1', element => element.textContent);
const itemTexts = await page.$$eval(
'li',
elements => elements.map(element => element.textContent)
);
Choose the all-match form when the page can contain multiple results and you need to process them together. Do not assume the first-match form has a match: if a required element may be absent, arrange an explicit wait or handle the absence rather than letting later code operate on a nonexistent element. The examples illustrate the documented APIs; they do not imply that a particular selector matches on every site.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Wait explicitly when you need a DOM condition
Use page.waitForSelector(selector, options) when the script must pause until a selector is present, or until it satisfies the visibility condition you request.
const element = await page.waitForSelector('[data-testid="ready"]', {
visible: true,
timeout: 30_000
});
if (element) {
// Use the ElementHandle, then release it when finished.
await element.dispose();
}
The documented default timeout is 30,000 milliseconds. Options include visible, hidden, timeout, and signal. A timeout failure throws, so code after the wait will not run unless you catch the error. A wait for a hidden selector can resolve to null when the selector is not found in the DOM. Read the exact option behavior in the Page.waitForSelector() API reference.
Rank #3
- Stunning 15.6" FHD IPS Display: Experience crisp 1920x1080 resolution on this 15.6 inch laptop with an IPS panel that delivers wide viewing angles and vivid colors. The narrow-bezel design maximizes screen real estate for comfortable viewing on this Win 11 laptop, whether you're studying or working.
- Celeron J4105 Processor & 256GB SSD: Powered by a reliable Celeron J4105 processor paired with 12GB DDR4 memory and a fast 256GB M.2 SSD. This laptop computer supports SSD expansion up to 2TB and TF card expansion up to 1TB, so your storage grows with your needs. Delivers smooth multitasking for daily productivity.
- AI-Powered Win 11 Laptop: Built-in AI features enhance your productivity with smart assistance for writing, summarizing, and task management. Pre-installed with Win 11 and includes Office 365 subscription. This student laptop is backed by 1-year warranty and 24/7 customer support.
- All-Day 7000mAh Battery & 180° Hinge: The high-capacity 7000mAh battery keeps this laptop powered through long classes or meetings. The 180-degree lay-flat hinge lets you share your screen effortlessly during presentations. This durable laptop computer adapts to your dynamic workflow.
- Versatile Connectivity Hub: Equipped with USB 3.2, Type-C, Mini HDMI, and 3.5mm audio jack to connect all your peripherals. Stay online anywhere with high-speed 5G WiFi and Bluetooth 4.2. This college laptop keeps you connected at home, in the library, or on the go.
Waiting for a selector is not the same as making a later action retry automatically. The wait establishes the requested DOM condition; it does not promise that an action attempted afterward will remain possible if the page changes. If your goal is simply to click or fill a control, a locator is usually a more direct expression of that goal. If you explicitly need an element handle or a point in the script at which to wait, use waitForSelector(), then manage the handle’s lifetime.
Know when CSS is not enough
CSS is the right choice when you can identify an element by its DOM tag, class, ID, attributes, or structural relationship. CSS selectors do not, however, select by visible text or accessible name, and ordinary CSS selection does not cross into a Shadow DOM. Puppeteer documents additional selector syntax for those cases in its Page interactions guide.
| What identifies the target | Selector approach | When it helps |
|---|---|---|
| Tag, class, ID, attribute, or DOM relationship | Ordinary CSS, such as button.primary |
Use this for standard DOM structure and attributes. |
| Text | ::-p-text(...) |
Use Puppeteer’s text selector when the target is best identified by its text rather than its CSS attributes. |
| Computed accessible name or role | ::-p-aria(...) |
Use the documented ARIA selector when the accessible name or role is the useful identifier. |
| XPath expression | ::-p-xpath(...) |
Use when the query is naturally expressed in XPath rather than CSS. |
| Element inside an open shadow root | The >>> deep descendant combinator |
For example, my-custom-element >>> button traverses open shadow roots. |
Use the documented forms such as ::-p-text(...), ::-p-aria(...), and ::-p-xpath(...) rather than relying on the older prefixed text/, aria/, xpath/, or pierce/ forms, which the guide identifies as legacy syntax. For shadow content, the documented deep combinator traverses open shadow roots; ordinary CSS does not descend into Shadow DOM.
Complete example: find and use a matching element
This example makes the choice explicit: it uses a locator for an interaction that should wait for a ready control. Replace the page URL and selector with the site and element your script needs.
const puppeteer = require('puppeteer');
async function run() {
const browser = await puppeteer.launch();
try {
const page = await browser.newPage();
await page.goto('https://example.com');
// CSS is accepted directly. The locator waits for action readiness.
await page.locator('button.primary').click();
// Read all current matches as values rather than retaining handles.
const itemTexts = await page.$$eval(
'li',
elements => elements.map(element => element.textContent?.trim() ?? '')
);
console.log(itemTexts);
} finally {
await browser.close();
}
}
run().catch(error => {
console.error(error);
process.exitCode = 1;
});
The example demonstrates selector use and cleanup of the browser. It assumes the target page and selector are appropriate for the task; a selector that does not identify the intended element must be corrected. If the script needs a handle rather than an action, replace the locator interaction with page.$() or page.$$(), check for null or an empty array, and dispose of handles after use.
Rank #4
- Efficient Performance for Everyday Computing: Powered by Intel N150 processor with up to 3.6 GHz Intel Turbo Boost Technology, 6 MB L3 cache, 4 cores, and 4 threads, this HP laptop delivers responsive performance for web browsing, streaming, document editing, and multitasking. Paired with 4GB LPDDR5 RAM and 128GB UFS storage, it handles daily tasks smoothly. Includes 1-year Microsoft 365 Personal subscription for Word, Excel, PowerPoint, and cloud storage to maximize your productivity.
- 14-Inch HD Micro-Edge Display:Enjoy clear visuals on the 14-inch HD (1366 x 768) anti-glare screen with 250-nit brightness and 62.5% sRGB coverage. The micro-edge bezel delivers a 79% screen-to-body ratio in a compact design. An HP True Vision 720p HD camera with noise reduction and dual-array microphones supports clear video calls, remote work, and online learning.
- Modern Connectivity and Wireless Technology: Stay connected with Wi-Fi 6 (2x2) for faster wireless speeds and Bluetooth 5.4 for seamless pairing with accessories. Versatile port selection includes 1 USB Type-C 10Gbps with DisplayPort 1.2 for external displays, 2 USB Type-A 5Gbps ports for peripherals, 1 HDMI 1.4b port, 1 headphone/microphone combo jack, and 1 multi-format SD media card reader. Connect monitors, transfer files quickly, and expand your workspace with ease.
- All-Day Battery Life and Portable Design: Enjoy up to 11 hours of video playback, 7.5 hours of mixed usage, or 7.5 hours of wireless streaming on a single charge, perfect for students and professionals on the go. Weighing just 3.24 lb and measuring 12.76" x 8.86" x 0.71", this lightweight laptop fits easily in backpacks and bags. The stylish willow green top cover with matte finish and natural silver keyboard deck with vertical brushing pattern offer a modern, professional look.
- AI-Enhanced Productivity: Access Microsoft Copilot instantly with the dedicated Copilot key for faster assistance. AI Noise Reduction filters background sounds and improves voice clarity during calls. Dual speakers provide clear audio, while the full-size natural silver keyboard and HP Imagepad support comfortable typing and navigation.
Troubleshoot selector failures
- The query returns
nullor[]. The selector had no match at the time of the query. Verify the selector against the page’s actual DOM and confirm the relevant content has loaded. Usepage.waitForSelector()if you need to wait for a match, or a locator for an action that should wait for readiness. waitForSelector()times out. Its requested condition was not met before the timeout. Check that the selector is correct and that the target is expected to appear or become visible. Increase the timeout only when a longer wait is appropriate; a larger value does not repair a selector that can never match.- A hidden wait gives
null. The documented hidden behavior can resolve tonullwhen the selector is absent from the DOM. Make that result part of the control flow instead of assuming it is an element handle. - A handle operation fails after selection. A handle is not a substitute for an ongoing locator action. The page may change after a query; use a locator for interactions that need readiness checks, and dispose of handles when finished.
- A CSS selector does not find text or an accessible name. Those are not ordinary CSS attributes. Use Puppeteer’s documented text or ARIA selector syntax where appropriate.
- A selector fails for content inside a shadow root. CSS selection does not descend into Shadow DOM. For open shadow roots, use the documented
>>>deep descendant combinator. - A long structural selector breaks after a layout change. Reconsider whether the selector depends on incidental nesting. A specific ID, class, or attribute can be clearer and less coupled to surrounding markup when the page provides one.
Or skip the browser setup
If your goal is to capture a page rather than interact with its DOM, ScreenshotNeo provides a screenshot API: one GET request accepts a URL and returns an image or PDF. This does not replace Puppeteer when you need custom browser logic or element-level interaction, but it avoids setting up a browser just to capture a page.
cURL example, with the endpoint and parameter format documented at ScreenshotNeo documentation:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
- Cookie and consent banners are accepted before capture, and more than 60 known consent platforms, newsletter popups, and chat widgets are removed; each step can be turned off.
- Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed; responses include
X-Page-VerdictandX-Billedheaders. - An MCP server provides
take_screenshot,get_page_info, andcapture_pdftools for Claude, Cursor, and other MCP clients. - The free plan includes 1,000 screenshots per month with no card required; paid plans start at $5 for 3,000 screenshots.
Sign up for ScreenshotNeo and get 1,000 screenshots a month free, with no card.
Performance, reliability, and cost considerations
Choose the lightest API that satisfies the task. A locator expresses an action and its readiness conditions; $eval() and $$eval() return values through a page function; $() and $$() create element handles that your code must manage. Avoid retaining handles longer than needed, and dispose of them when finished. For an explicit wait, use the timeout intentionally and account for its failure path.
There is no universal speed figure for a selector API in the cited Puppeteer guidance, and the selector examples are not a benchmark. In practice, the selector strategy should first be correct and appropriately scoped; waiting behavior, page state, and the work your script performs are distinct from whether the selector string is CSS. Do not treat a successful selector lookup as proof that subsequent page content will remain unchanged.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Best Value
- Designed for mobility with a slim 0.71-inch profile and lightweight 3.24 lb chassis, making it easy to carry between home, office
Puppeteer’s selector APIs are library operations; the referenced pages do not state a per-selector charge. If the task is only obtaining screenshots rather than querying or acting on page elements, an API service such as ScreenshotNeo is a different workflow with its own published plan allowances. It is not a replacement for selector logic when your task depends on locating and manipulating elements.
Frequently Asked Questions
Does Puppeteer require a special prefix for CSS selectors?
No. CSS selectors are accepted directly by Puppeteer selector APIs.
Which selector method should I use to click a button?
Use a locator, for example await page.locator('button.primary').click(), so the interaction can wait for its documented readiness conditions.
Can ordinary CSS find an element inside a shadow root?
No. The documented >>> combinator traverses open shadow roots.
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.




