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.

Use a Puppeteer locator and click it directly: await page.locator('button[data-testid="load-more"]').click();. A locator can be created before the button exists, waits for the element to become actionable, and retries when the target is not ready. Replace the selector with one that uniquely identifies your page’s button.

Use a locator for the dynamic button

Puppeteer’s current Page interactions guide says, “Locators is the recommended way to select an element and interact with it.” A locator is lazy: creating it does not require the element to be present yet. Puppeteer resolves it when you perform the action.

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();

await page.goto('https://example.com/app', { waitUntil: 'domcontentloaded' });

await page.locator('button[data-testid="load-more"]').click();

await browser.close();

During a locator click, Puppeteer waits until the matched element is in the viewport, visible, enabled, and has a stable bounding box across two animation frames. If the element is inserted later or is temporarily not actionable, the locator operation retries. This is generally safer than guessing how many milliseconds a framework needs to render.

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

The exact selector is application-specific. Inspect the button in browser developer tools and prefer a stable attribute such as data-testid, an accessible name, or a semantic relationship. The simple page.locator('button').click() example works only when there is exactly one relevant button; a broad selector can click the wrong control.

#1 Best Overall
Sale
Logitech M185 Compact Ambidextrous 2.4 GHz Wireless Mouse - Swift Grey
  • Compact Mouse: With a comfortable and contoured shape, this Logitech ambidextrous wireless mouse feels great in either right or left hand and is far superior to a touchpad
  • Durable and Reliable: This USB wireless mouse features a line-by-line scroll wheel, up to 1 year of battery life (2) thanks to a smart sleep mode function, and comes with the included AA battery
  • Universal Compatibility: Your Logitech mouse works with your Windows PC, Mac, or laptop, so no matter what type of computer you own today or buy tomorrow your mouse will be compatible
  • Plug and Play Simplicity: Just plug in the tiny nano USB receiver and start working in seconds with a strong, reliable connection to your wireless computer mouse up to 33 feet / 10 m (5)
  • Better than touchpad: Get more done by adding M185 to your laptop; according to a recent study, laptop users who chose this mouse over a touchpad were 50% more productive (3) and worked 30% faster (4)

Choose a selector that identifies the intended button

Stable attributes

A meaningful attribute is usually the most resilient option.

await page.locator('button[data-testid="load-more"]').click();
await page.locator('button[aria-label="Open filters"]').click();
await page.locator('#checkout-submit').click();

Avoid generated class names, positional selectors such as button:nth-of-type(4), and CSS paths that encode the entire layout. They often change when a component is rebuilt.

Button text

When the visible label is the stable clue, filter a button locator by its text. The predicate runs against each candidate’s text content.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
await page
  .locator('button')
  .filter(button => button.textContent?.trim() === 'Load more')
  .click();

Use an exact comparison when labels such as “Delete” and “Delete permanently” must not be confused. If the site localizes text, an accessible name, test identifier, or other language-independent attribute is preferable.

Accessibility and custom selectors

Puppeteer supports custom selector forms documented in its page-interactions guide, including text and accessibility selectors:

Rank #2
Sale
Logitech G305 Lightspeed Wireless Gaming Mouse - Black
  • The next-generation optical HERO sensor delivers incredible performance and up to 10x the power efficiency over previous generations, with 400 IPS precision and up to 12,000 DPI sensitivity
  • Ultra-fast LIGHTSPEED wireless technology gives you a lag-free gaming experience, delivering incredible responsiveness and reliability with 1 ms report rate for competition-level performance
  • G305 wireless mouse boasts an incredible 250 hours of continuous gameplay on just 1 AA battery; switch to Endurance mode via Logitech G HUB software and extend battery life up to 9 months
  • Wireless does not have to mean heavy, G305 lightweight mouse provides high maneuverability coming in at only 3.4 oz thanks to efficient lightweight mechanical design and ultra-efficient battery usage
  • The durable, compact design with built-in nano receiver storage makes G305 not just a great portable desktop mouse, but also a great laptop travel companion, use with a gaming laptop and play anywhere
await page.locator('::-p-text(Load more)').click();
await page.locator('::-p-aria(Load more)').click();

Narrow these selectors when multiple matches are possible. A selector that resolves to more than one candidate should be refined with a container, attribute, or filter.

Wait for the result, not an arbitrary delay

A click can be actionable before the application has finished its work. If clicking “Load more” appends cards, wait for a condition that proves the append completed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const cards = page.locator('[data-testid="result-card"]');
const before = await cards.count();

await page.locator('button[data-testid="load-more"]').click();
await page.locator('[data-testid="result-card"]').nth(before).wait();

If the only requirement is that a loading indicator become visible, a locator can wait for that state:

await page.locator('.loading').wait();

For a disappearing spinner, wait for the opposite condition with a selector or application-specific assertion. The important distinction is that a fixed sleep is only a pause; it does not prove that rendering, a request, or state reconciliation has completed.

When the click triggers navigation

Start the navigation wait and the click together. This prevents a race in which navigation begins before a separately scheduled wait is listening.

Rank #3
Sale
Logitech M185 Compact Ambidextrous Wireless Mouse with Rubber Grips - Blue
  • Compact Mouse: With a comfortable and contoured shape, this Logitech ambidextrous wireless mouse feels great in either right or left hand and is far superior to a touchpad
  • Durable and Reliable: This USB wireless mouse features a line-by-line scroll wheel, up to 1 year of battery life (2) thanks to a smart sleep mode function, and comes with the included AA battery
  • Universal Compatibility: Your Logitech mouse works with your Windows PC, Mac, or laptop, so no matter what type of computer you own today or buy tomorrow your mouse will be compatible
  • Plug and Play Simplicity: Just plug in the tiny nano USB receiver and start working in seconds with a strong, reliable connection to your wireless computer mouse up to 33 feet / 10 m (5)
  • Better than touchpad: Get more done by adding M185 to your laptop; according to a recent study, laptop users who chose this mouse over a touchpad were 50% more productive (3) and worked 30% faster (4)
const [response] = await Promise.all([
  page.waitForNavigation(),
  page.locator('button[data-testid="continue"]').click(),
]);

console.log('Arrived at:', response?.url() ?? page.url());

If the button updates the current document without navigation, do not wait for navigation. Instead, wait for the new URL, a heading, a dialog, or another element that represents the expected state.

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

Lower-level alternative: waitForSelector and an ElementHandle

waitForSelector remains useful when you need an explicit element handle or lower-level control.

const button = await page.waitForSelector(
  'button[data-testid="load-more"]',
  { visible: true },
);

if (!button) {
  throw new Error('Button was not found');
}

await button.click();
await button.dispose();

According to Puppeteer’s Page.waitForSelector API, the call resolves immediately if the selector already matches; otherwise it waits until it does. Its documented default timeout is 30 seconds, configurable per call or through the page’s default timeout. The visible option requires the element to have a non-hidden rendered state. Other supported controls include hidden and an AbortSignal.

This approach waits for the selector, but the returned handle’s click() does not provide the locator’s full actionability-and-retry behavior. A handle can also become stale if a frontend framework replaces the node between the wait and the click. Dispose of handles you no longer need.

Dynamic buttons in Shadow DOM

Normal CSS selectors do not cross a shadow boundary. For an open shadow root, use Puppeteer’s deep combinator:

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.
Rank #4
Amazon Basics 3-Button USB Wired Mouse with Responsive Tracking, Plug & Play, Compatible with Windows and Mac, Black
  • Computer mouse for easily navigating a computer interface; click, scroll, and more
  • USB-A wired connection; if existing device only supports USB-C, an additional adapter will be required
  • High-definition (1000 dpi) optical tracking ensures responsive cursor control for precise tracking and easy text selection
  • 3 buttons offer effortless fingertip control
  • Plug-and-go ready for instant use
await page.locator('my-toolbar >>> button[data-testid="save"]').click();

The host and internal selector depend on the component tree. Closed shadow roots cannot be queried this way; use a supported public control or an application-level test hook instead. Text and accessibility selector forms can also help when the component exposes its contents through the accessibility tree.

Dynamic buttons inside an iframe

An iframe has a separate document. Querying the main page for a button inside it will return no match. Obtain the frame and use its locator or selector API.

const frame = page.frames().find(f => f.url().includes('/checkout'));
if (!frame) throw new Error('Checkout frame was not found');

await frame.locator('button[data-testid="pay-now"]').click();

For a frame that appears after a user action, wait for its URL or name before selecting elements. Cross-origin frames still have isolated documents; Puppeteer’s frame APIs handle the browser context, but your selector must belong to that frame.

Common failures and precise fixes

Timeout: no element matched

  • Cause: the selector is wrong, the page has not reached the route that renders the button, or the button is inside a frame or shadow root.
  • Fix: log page.url(), inspect the rendered DOM, verify the frame, and use the appropriate deep selector. Increase the timeout only after confirming the selector and page state.

The first matching button is wrong

  • Cause: a generic selector such as button matches menus, cookie controls, or hidden component instances.
  • Fix: add a test identifier, accessible name, container, or exact text filter. Puppeteer’s Page.click reference documents first-match behavior for selector-based clicks.

Element is visible but not clickable

  • Cause: an overlay covers it, it is disabled, it is moving, or the frontend has not completed its transition.
  • Fix: wait for the overlay to disappear, wait for the button’s enabled state or resulting locator, and avoid coordinate clicks. Locator actionability checks require visibility, enabled state, viewport presence, and a stable bounding box.

Click succeeds but nothing is ready afterward

  • Cause: the click started an asynchronous request or state update.
  • Fix: wait for the resulting element, URL, dialog, or application signal. Do not substitute an arbitrary sleep for an observable condition.

Navigation wait hangs

  • Cause: the button performs an in-page update rather than navigation, or the navigation event happened before the wait was installed.
  • Fix: use the Promise.all pattern shown above for real navigation; otherwise wait for the in-page result.

ElementHandle becomes detached

  • Cause: a reactive framework replaced the DOM node after waitForSelector returned.
  • Fix: prefer a locator, which re-resolves the target during the action, or reacquire the handle immediately before clicking.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Timeouts, retries, and reliability

Keep the default timeout when the page normally responds quickly, and set a deliberate upper bound for slower environments:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
page.setDefaultTimeout(15_000);
await page.locator('button[data-testid="load-more"]').click();

A longer timeout can accommodate a slow test environment, but it cannot repair a selector that never matches. For reliable suites, assert the page URL after navigation, capture useful diagnostics on failure, and wait for business outcomes rather than implementation details.

Best Value
Sale
Acer Wireless Mouse for Laptop, 2.4GHz Computer Mouse 3 Adjustable 1600 DPI
  • 【Plug and Play for Home/Office/School】The wireless computer mouse features 2.4GHz connectivity, delivering a stable, interference-free connection up to 32ft. Designed for 𝐦𝐞𝐝𝐢𝐮𝐦 𝐭𝐨 𝐥𝐚𝐫𝐠𝐞 𝐬𝐢𝐳𝐞𝐝 𝐡𝐚𝐧𝐝𝐬, it ensures comfortable use all day. Simply plug in the USB-A receiver for instant pairing—no drivers needed. 📌📌 If the mouse isn’t suitable, place the USB receiver in the battery compartment and return both.
  • 【3 Levels Adjustable DPI】This travel USB mouse offers 3 adjustable DPI settings (800, 1200, 1600), allowing you to customize sensitivity for precise design work. Effortlessly switch to match your task and elevate your productivity. 📌 Please remove the film at the bottom of the mouse before use.
  • 【Effortless Browsing】Equipped with forward and backward buttons, this computer mice streamlines your workflow, making it easy to navigate through web pages and files with a simple click. 📌Side button does not work on Mac.
  • 【Visible Indicator Light】 The pc mouse features a visual indicator for DPI levels and low battery alerts. The red light flashes once for 800 DPI, twice for 1200 DPI, and three times for 1600 DPI. When the battery level is below 10%, the light flashes red until the mouse is completely out of power.
  • 【Click to Wake】With smart sleep mode, it saves power by standby after 10 inactive minutes, just 2-3 clicks to wake. This efficient design delivers 3x longer battery life than motion-wake mice. Engineered for durability, its buttons and scroll wheel are tested for 10 million clicks, ensuring long-term reliability and consistent performance.

Locator retries are helpful for insertion and transient actionability, not for infinite application failures. If a button remains disabled because validation failed, automation should surface that state instead of clicking around it.

Or skip the browser setup

If your goal is a clean image or PDF of a page rather than an interaction test, ScreenshotNeo makes one GET request and returns a PNG, JPEG, WebP, or PDF. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and whether it was billed. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

See the ScreenshotNeo documentation for all options. A direct call looks like this:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://example.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots, and every feature is available on every plan. Create a free ScreenshotNeo account.

Quick decision guide

Need Use Reason
Click a button that may appear later Locator Waits for action preconditions and retries.
Control a returned DOM handle waitForSelector Provides an explicit handle; dispose it afterward.
Button navigates Locator plus waitForNavigation in Promise.all Prevents navigation races.
Button is in a shadow root Deep combinator or custom selector Normal CSS does not cross shadow boundaries.
Button is in an iframe Frame locator The frame has a separate document.

Frequently Asked Questions

Can I create a Puppeteer locator before the button exists?

Yes. Locator creation is lazy; the element is resolved when you perform an action, so a button inserted later can still be clicked if the selector eventually matches.

Should I use a fixed delay before clicking?

Usually no. Use a locator or waitForSelector for readiness, then wait for the specific post-click condition your application produces.

What is Puppeteer’s documented default waitForSelector timeout?

The documented default is 30 seconds in the Page.waitForSelector API; configure it per call or with the page’s default timeout.

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

Why does my selector work on the page but not in an iframe?

Selectors run in the current document. Select the correct Puppeteer frame first, then query that frame for the button.

The Bottom Line

For a dynamically inserted button, start with a specific Puppeteer locator, coordinate navigation waits with the click when necessary, and query through the correct frame or shadow root when the DOM is isolated.

Quick Recap

SaleBestseller No. 1
Logitech M185 Compact Ambidextrous 2.4 GHz Wireless Mouse - Swift Grey
Logitech M185 Compact Ambidextrous 2.4 GHz Wireless Mouse - Swift Grey
Product carbon footprint: 3.97 kg CO2e; Contoured shape: Gives you more comfort and control
$14.90
SaleBestseller No. 3
Bestseller No. 4
Amazon Basics 3-Button USB Wired Mouse with Responsive Tracking, Plug & Play, Compatible with Windows and Mac, Black
Amazon Basics 3-Button USB Wired Mouse with Responsive Tracking, Plug & Play, Compatible with Windows and Mac, Black
Computer mouse for easily navigating a computer interface; click, scroll, and more; 3 buttons offer effortless fingertip control
$9.70

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.