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

Put await page.goto(url) inside your loop. Puppeteer will not start the next iteration until that navigation promise settles. Choose a waitUntil condition that matches the work you do next, and add an explicit selector or locator wait when a client-rendered element is the real readiness signal.

for (const url of urls) {
  await page.goto(url, { waitUntil: 'domcontentloaded' });
  // Parse the DOM or interact with the page here.
}

The basic sequential pattern

A for...of loop with await is the clearest way to process URLs one at a time with a reused Puppeteer Page. The loop pauses at page.goto(); only after that promise resolves does it inspect the page or move to the next URL.

import puppeteer from 'puppeteer';

const urls = [
  'https://example.com/',
  'https://example.org/'
];

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

for (const url of urls) {
  await page.goto(url, { waitUntil: 'domcontentloaded' });
  const title = await page.title();
  console.log(url, title);
}

await browser.close();

Install Puppeteer with npm install puppeteer and run this as an ES module (for example, save it as loop.mjs). If you omit waitUntil, Puppeteer uses the documented load lifecycle condition by default. The promise means “the selected navigation boundary was reached,” not “every useful application component has finished rendering.”

Choose the right navigation boundary

The best wait condition is determined by what the next statement needs. These lifecycle options are not interchangeable guarantees of application readiness.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Condition What it observes Use it when Main caveat
domcontentloaded The initial HTML has been parsed. You can read the DOM or run early, script-independent checks. Images, styles, fonts, and client-rendered data may still be loading.
load The page load event. The load event is the boundary your task requires, or you want Puppeteer’s documented default. It still does not prove that a single-page application has rendered its data.
networkidle0 No active network connections for the required idle period. The target really becomes quiet and network silence is meaningful. Polling, analytics, sockets, and other persistent requests can prevent or delay completion.
networkidle2 At most two active network connections for the required idle period. A page has background traffic but becomes mostly idle before your operation. “Mostly idle” is not the same as the application-specific content being ready.

Set the option per navigation when different URLs have different behavior:

await page.goto(url, {
  waitUntil: ['domcontentloaded', 'load'],
  timeout: 45_000
});

Use a finite timeout that reflects your workload. A timeout is a failure signal to handle, not evidence that a page can never load.

Wait for the content your script actually needs

For a server-rendered page, the lifecycle event may be sufficient. For a client-rendered page, wait for an observable application condition after navigation. page.waitForSelector() resolves when a matching element appears; with visible: true, it also requires the element to be visible. Its documented default timeout is 30 seconds.

for (const url of urls) {
  await page.goto(url, { waitUntil: 'domcontentloaded' });
  await page.waitForSelector('[data-ready="true"]', {
    visible: true,
    timeout: 30_000
  });

  const text = await page.$eval('[data-ready="true"]', el => el.textContent);
  console.log(url, text?.trim());
}

Replace [data-ready="true"] with a selector that represents a real state in your application: a results container, a table row, a success marker, or an error panel. Waiting for a generic element such as body rarely adds useful synchronization because it exists before the data arrives.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Use locators when interaction preconditions matter

Puppeteer locators can wait for presence, visibility, enabled state, and stable layout before interacting. They are useful when the next operation is a click or form submission rather than a simple DOM read.

await page.goto(url, { waitUntil: 'domcontentloaded' });
const next = page.locator('button.next');
await next.click();

The locator wait should still express your application’s condition. If a button is present but disabled while data loads, the interaction preconditions prevent an early click; if your workflow needs a particular response or text, wait for that state explicitly.

Waiting after a click that triggers navigation

page.goto() already waits for its own navigation. Do not append page.waitForNavigation() as a generic extra delay. Use waitForNavigation() for an action such as clicking a link that causes a subsequent navigation, and install the wait before the click.

const [response] = await Promise.all([
  page.waitForNavigation({ waitUntil: 'domcontentloaded' }),
  page.click('a.next')
]);

if (response) {
  console.log('Navigated to', response.url());
} else {
  console.log('The action did not produce a document navigation');
}

The concurrent pattern avoids a race in which the click starts navigation before the wait listener exists. The returned value is the main resource response for a document navigation, but it can be null for an anchor-only change or a History API transition. Code that assumes a response object for every click will fail on those cases.

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 #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Handle timeouts and per-URL failures deliberately

Puppeteer exposes a page-level default navigation timeout, and individual navigation calls can override it. Keep the timeout finite and record enough context to identify the URL and condition that failed.

page.setDefaultNavigationTimeout(45_000);

for (const url of urls) {
  try {
    await page.goto(url, {
      waitUntil: 'domcontentloaded',
      timeout: 45_000
    });
    await page.waitForSelector('main', {
      visible: true,
      timeout: 15_000
    });
    console.log(`OK ${url}`);
  } catch (error) {
    console.error(`FAILED ${url}`, error.message);
    // Record the failure and continue, or throw to stop the batch.
  }
}

The page-level setter affects goto(), waitForNavigation(), and related navigation operations. Wait methods also accept their own timeout. A timeout value of zero disables the timeout; use that only when you have an external cancellation policy, because a hung request can otherwise hold the whole loop indefinitely.

Continue or stop?

Puppeteer does not decide whether one bad URL should abort your run. Choose a policy that fits the job:

  • Fail fast: rethrow the error when every URL is required and a partial result is unsafe.
  • Record and continue: store the URL, error message, and wait condition when a batch should produce best-effort results.
  • Retry selectively: retry only errors you classify as transient, with a bounded attempt count and delay. Do not treat retries as an automatic Puppeteer feature.

Why common “extra waits” do not fix readiness

Adding waitForNavigation() after goto()

After goto() has resolved, the document navigation it started is already complete according to its wait condition. A second waitForNavigation() waits for a later navigation and can hang until its timeout.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Using network idle as a universal signal

Modern sites often keep connections open for analytics, polling, advertisements, or live updates. networkidle0 can therefore wait too long, while networkidle2 can resolve before the specific component you need is populated. Prefer a meaningful selector or application state when one exists.

Sleeping for a fixed number of milliseconds

A fixed sleep is either wasteful on fast pages or too short on slow pages. An element, text condition, response, or locator precondition adapts to the actual state and gives a more useful timeout error.

Performance and reliability in a URL loop

Sequential versus concurrent work

A sequential for...of loop is predictable and avoids competing navigations on one Page. It is usually the right default when each result depends on the previous operation or when the target site has strict request limits. Do not replace it with urls.forEach(async ...); forEach does not await the returned promises.

If throughput matters, create a controlled pool of pages or browser contexts and cap concurrency. Each worker should own its page and use the same explicit readiness and timeout rules. Launching unbounded tabs can exhaust memory, saturate your network, and trigger site defenses.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Make waits observable

  • Log the URL before navigation and after each readiness condition.
  • Include the selected waitUntil, selector, and timeout in failure records.
  • Capture the current URL and a short error message when a wait fails.
  • Separate navigation failures from selector failures so a slow server is not confused with a changed DOM.

Account for pages that never become quiet

For long-polling or streaming applications, use domcontentloaded followed by a selector or application-specific check. If the page renders a loading state and an error state, wait for either and branch accordingly instead of waiting forever for a success-only selector.

await page.goto(url, { waitUntil: 'domcontentloaded' });
await page.waitForFunction(() => {
  return document.querySelector('[data-status="ready"]') ||
         document.querySelector('[data-status="error"]');
}, { timeout: 20_000 });

const status = await page.$eval('[data-status]', el => el.dataset.status);
if (status === 'error') throw new Error(`Application reported an error for ${url}`);
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting checklist

Symptom Likely cause Fix
The next URL starts before the current one is processed. The loop does not await navigation, or it uses forEach with an async callback. Use for...of and await page.goto() inside the loop.
waitForNavigation() times out after goto(). It was added after the navigation already completed. Remove it, or pair it with the click/action that starts a new navigation.
networkidle0 never resolves. Persistent requests keep the page active. Use domcontentloaded plus a selector or application condition.
A selector wait times out even though the page looks loaded. The selector is wrong, content is inside a frame or shadow root, or the app rendered an error state. Verify the selector in DevTools, inspect frames and shadow DOM, and wait for a success-or-error condition.
A click navigation returns null. The action changed the URL through a hash or History API without a document navigation. Check the resulting URL or wait for the DOM state that proves the route changed.
Some URLs fail while others work. That origin is slow, blocked, intermittently unavailable, or has different markup. Log the URL and wait condition, use a realistic finite timeout, and apply a bounded retry policy only where appropriate.
The browser process remains after errors. browser.close() was skipped on an exception. Wrap the run in try...finally and close the browser in the finally block.

Or skip the browser setup

If your goal is a clean image or PDF rather than browser automation logic, ScreenshotNeo provides a single HTTP request. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and the response identifies the result with X-Page-Verdict and X-Billed headers.

Use the API documentation at https://screenshotneo.com/docs/ for the full option set. This example captures Stripe as a WebP image:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo also offers an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. Options include full-page screenshots with lazy images loaded, CSS-selector element capture, dark mode, 12 device presets or custom viewports, retina scale, PDF paper sizes and page ranges, custom CSS and JavaScript, click-before-capture, selector or network-idle waits, request and resource blocking, custom headers/cookies/user agents, authorization, timezone and geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Common parameter names used by other screenshot APIs also work.

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

The Free plan includes 1,000 shots each month with no card. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free, and every feature is available on every plan. Sign up free for ScreenshotNeo and start with the 1,000 monthly shots.

Frequently Asked Questions

How can I check the HTTP status returned by a navigation?

Store the value returned by page.goto() and inspect it only when it is non-null: const response = await page.goto(url); const status = response?.status();. A null response means Puppeteer did not receive a document response, so handle that case separately.

What is the safest way to close the browser when a loop throws?

Create the browser before the loop and put the loop in a try block with await browser.close() in finally. This cleanup runs for both successful completion and navigation errors.

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.