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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Read a JSON file, validate its URL list, then use Puppeteer to visit each URL and save a separate screenshot. The example below assumes this input shape: {"urls":["https://example.com","https://example.org"]}. It processes URLs sequentially, saves viewport PNGs, continues after an individual capture fails, and always closes the browser.

Set up the JSON input and Puppeteer

Use Node.js with Puppeteer’s managed Chrome for Testing browser. Puppeteer’s official guide demonstrates the core flow: launch a browser, open a page, navigate, call Page.screenshot(), and close the browser (Puppeteer screenshots guide). Install Puppeteer in a new project:

npm init -y
npm install puppeteer

Create urls.json in the project directory:

{
  "urls": [
    "https://example.com",
    "https://example.org"
  ]
}

The urls property and array-of-strings format are assumptions for this script, not a requirement imposed by Puppeteer. The script rejects invalid JSON or a missing or incorrectly typed urls property before starting Chrome. It skips blank entries and reports malformed or unsupported URL values individually.

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

Run a sequential screenshot script

Save the following as capture.js, alongside urls.json, then run node capture.js. It writes PNG files to a new screenshots folder, with a zero-padded index and hostname in each filename. Query strings and URL paths are not used as filenames, so they cannot accidentally create nested paths or overwrite another URL’s file.

#1 Best Overall
Sale
Epson Workforce ES-50 Compact & Lightweight Mobile Document Scanner
  • PORTABLE SCANNER FOR USE ON-THE-GO — The fastest and lightest mobile single-sheet-fed compact document scanner in its class¹
  • QUICK DOCUMENT SCANNING ― This Epson ultra-fast scanner scans a single page as quickly as 5.5 seconds²; Windows and Mac compatible
  • VERSATILE PAPER HANDLING ― Portable scanner scans documents up to 8.5 x 72 in; Also easily digitizes receipts and ID cards to make accounting, bookkeeping, and organizing simpler
  • INTUITIVE, HIGH-SPEED SOFTWARE — Epson ScanSmart Software³ is a smart tool allowing you to easily scan, review, and save; Stay organized easily with the help of this Epson scanner
  • EASY SETUP — USB-powered connect to your computer for quick and simple scanning; No batteries or external power supply required to operate portable document scanner; Standard Connectivity: USB 2.0
const fs = require('node:fs/promises');
const path = require('node:path');
const puppeteer = require('puppeteer');

const inputPath = path.join(__dirname, 'urls.json');
const outputDir = path.join(__dirname, 'screenshots');

async function readUrls() {
  let text;
  try {
    text = await fs.readFile(inputPath, { encoding: 'utf8' });
  } catch (error) {
    throw new Error(`Could not read ${inputPath}: ${error.message}`);
  }

  let data;
  try {
    data = JSON.parse(text);
  } catch (error) {
    throw new Error(`Invalid JSON in ${inputPath}: ${error.message}`);
  }

  if (!data || typeof data !== 'object' || !Array.isArray(data.urls)) {
    throw new Error('Expected a JSON object with a "urls" array.');
  }
  if (!data.urls.every((value) => typeof value === 'string')) {
    throw new Error('Every entry in "urls" must be a string.');
  }
  return data.urls;
}

function parseHttpUrl(value, index) {
  const trimmed = value.trim();
  if (!trimmed) {
    console.error(`Skipping URL ${index + 1}: value is blank.`);
    return null;
  }

  try {
    const url = new URL(trimmed);
    if (url.protocol !== 'http:' && url.protocol !== 'https:') {
      throw new Error('only http and https URLs are supported');
    }
    return url;
  } catch (error) {
    console.error(`Skipping URL ${index + 1}: ${error.message}`);
    return null;
  }
}

async function main() {
  const values = await readUrls();
  await fs.mkdir(outputDir, { recursive: true });

  let browser;
  const failures = [];
  let completed = 0;

  try {
    browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.setViewport({ width: 1365, height: 768, deviceScaleFactor: 1 });

    for (let index = 0; index < values.length; index += 1) {
      const url = parseHttpUrl(values[index], index);
      if (!url) continue;

      const filename = `${String(index + 1).padStart(4, '0')}-${url.hostname.replace(/[^a-zA-Z0-9.-]/g, '_')}.png`;
      const screenshotPath = path.join(outputDir, filename);

      try {
        await page.goto(url.href, {
          waitUntil: 'networkidle2',
          timeout: 30000
        });
        await page.screenshot({ path: screenshotPath });
        completed += 1;
        console.log(`Saved ${screenshotPath}`);
      } catch (error) {
        failures.push({ index: index + 1, host: url.hostname, message: error.message });
        console.error(`Failed URL ${index + 1} (${url.hostname}): ${error.message}`);
      }
    }
  } finally {
    if (browser) await browser.close();
  }

  console.log(`Finished: ${completed} screenshot(s) saved, ${failures.length} capture failure(s).`);
  if (failures.length) process.exitCode = 1;
}

main().catch((error) => {
  console.error(error.message);
  process.exitCode = 1;
});

The file read uses Node’s promise-based fs.readFile with UTF-8 encoding. Node documents this operation as reading the entire file into memory; for very large inputs, use a streaming or chunked design instead (Node.js filesystem documentation). The script reports errors by URL index and hostname rather than printing the full URL, which avoids exposing URL query values that may contain tokens.

Choose when a page is ready to capture

The example uses waitUntil: 'networkidle2', also shown in Puppeteer’s screenshot guide. It is a useful starting point, not proof that every page has finished rendering. Analytics, polling, streaming requests, or other persistent network activity can delay or prevent network idleness; a client-rendered page may also populate its important content after network activity settles.

Use a page-specific signal for dynamic content

If the screenshot depends on a particular element appearing, wait for it after navigation:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
await page.goto(url.href, { waitUntil: 'domcontentloaded', timeout: 30000 });
await page.waitForSelector('[data-ready="true"]', { timeout: 15000 });
await page.screenshot({ path: screenshotPath });

Replace the selector with a signal that means the target page is ready, such as a report container or a specific heading. If the site offers an application-specific readiness signal, use that rather than assuming that a generic browser event means the content is complete. Puppeteer also provides page.waitForNetworkIdle(); it resolves after the network is idle and waits at least the configured idle time, but it is not a universal completion test (Page.waitForNetworkIdle API).

Rank #2
Sale
Brother DS-640 Compact Mobile Document Scanner, (Model: DS640)
  • FAST SPEEDS - Scans color and black and white documents a blazing speed up to 16ppm (1). Color scanning won’t slow you down as the color scan speed is the same as the black and white scan speed.
  • ULTRA COMPACT – At less than 1 foot in length and only about 1. 5lbs in weight you can fit this device virtually anywhere (a bag, a purse, even a pocket).
  • READY WHENEVER YOU ARE – The DS-640 mobile scanner is powered via an included micro USB 3. 0 cable allowing you to use it even where there is no outlet available. Plug it into you PC or laptop and you are ready to scan.
  • WORKS YOUR WAY – Use the Brother free iPrint&Scan desktop app for scanning to multiple “Scan-to” destinations like PC, Network, cloud services, Email and OCR. (2) Supports Windows, Mac and Linux and TWAIN/WIA for PC/ICA for Mac/SANE drivers. (3)
  • OPTIMIZE IMAGES AND TEXT – Automatic color detection/adjustment, image rotation (PC only), bleed through prevention/background removal, text enhancement, color drop to enhance scans. Software suite includes document management and OCR software. (4)

Set a delay only when the page needs one

For content that appears after a known client-side delay and has no useful selector, wait explicitly before capturing:

await page.goto(url.href, { waitUntil: 'domcontentloaded', timeout: 30000 });
await new Promise((resolve) => setTimeout(resolve, 2000));
await page.screenshot({ path: screenshotPath });

A fixed delay is a compromise: a longer wait costs time for every URL, while a shorter one may capture too early. Prefer a meaningful selector where possible.

Choose screenshot dimensions and output

The script sets a 1365-by-768 viewport at device scale factor 1 and saves the visible viewport as PNG. Change the viewport before navigation if you need a different desktop or mobile layout. A viewport capture is bounded by the configured dimensions; full-page capture can produce a much taller, larger image.

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

Capture the full page

Pass fullPage: true to include the full scrollable page:

Rank #3
Sale
Canon imageFORMULA R10 - Portable Document Scanner, USB Powered, Duplex Scanning, Document Feeder, Easy Setup, Convenient, Perfect for Mobile Users, White
  • STAY ORGANIZED – Easily convert your paper documents into digital formats like searchable PDF files, JPEGs, and more.Power Consumption : 2.5W or less (Energy Saving Mode: 0.7W). Suggested Daily Volume : 500 scans..Does it contain liquid: no
  • CONVENIENT AND PORTABLE –lightweight and small in size, you can take the scanner anywhere from home offices, classrooms, remote offices, and anywhere in between
  • HANDLES VARIOUS MEDIA TYPES – Digitize receipts, business cards, plastic or embossed cards, reports, legal documents, and more
  • FAST AND EFFICIENT – No technical hurdles or complicated setups here; easily scan both sides of a document at the same time, in color or black-and-white, at up to 12 pages-per-minute, and with a 20 sheet automatic feeder
  • BROAD COMPATIBILITY – Works with both Windows and Mac devices, be it laptop or computer
await page.screenshot({ path: screenshotPath, fullPage: true });

Puppeteer’s screenshot options include path, type, fullPage, clip, omitBackground, and quality. fullPage defaults to false; the filename extension can determine the image type when one is not explicitly set. JPEG quality applies when using JPEG output. See the ScreenshotOptions API for the current option details.

Capture a region or choose another image format

To capture a specific rectangle, provide a clip object with its position and dimensions. To choose a format explicitly, use type:

await page.screenshot({
  path: screenshotPath,
  type: 'jpeg',
  quality: 85,
  clip: { x: 0, y: 0, width: 800, height: 600 }
});

For a transparent background, use omitBackground: true with a format that supports transparency, such as PNG. Avoid combining options without checking their applicability in the Puppeteer API, particularly format-specific quality settings.

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

Handle browser setup and batch size

The example launches Puppeteer’s managed Chrome for Testing browser. Puppeteer says it works best with that downloaded browser and does not guarantee compatibility with arbitrary browser versions. If you instead install puppeteer-core, configure executablePath or channel when launching; otherwise, the browser location is not specified for it. Consult the launch API for launch configuration.

Rank #4
IRIScan Express 4 Black Compact Portable USB Simplex Document Scanner, 8 PPM for Contracts, Invoices and Business Cards, Compatible with Windows, Readiris PDF Included
  • IRIScan Express, portable scanner : scans color and black and white documents a blazing speed up to 8ppm simplex. Color scanning won’t slow you down as the color scan speed is the same as the black and white scan speed.
  • IRIScan Express mobile scanner is powered via an included micro USB 2. 0 cable allowing you to use it even where there is no outlet available. Plug it into you PC or laptop and you are ready to scan. USB cable provided. AC Adapter not provided and not needed.
  • IRIScan flatbed scanner uses a simplex scanning mode allows for quick and straightforward scanning of single-sided documents. IRIScan with its full portable features is the ideal document scanners for computers.
  • IRIScan document scanner : Versatile scanning capabilities, including scanning to Word, PDF, and Excel formats with companion software provided Readiris OCR
  • Receipt scanner and card scanner with Additional features include scanning business cards directly to Outlook, photo scanning, and receipt scanning for efficient document management

Captures run sequentially, one URL at a time, sharing one page. This is a straightforward choice for moderate batches and predictable resource use. If throughput matters, consider a bounded number of concurrent pages, but choose the limit for your machine and pages and measure it: there is no universal safe concurrency number established here. More simultaneous pages consume more browser resources and can make failures harder to isolate.

The script keeps going after a navigation or screenshot error, records the failure, and exits with a nonzero status at the end if any captures failed. This makes it practical in automation while still surfacing an unsuccessful batch. The browser closes in finally, including when capture work throws. A process termination or machine shutdown cannot be handled by that cleanup path.

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

Troubleshoot common failures

  • “Could not read” the JSON file: confirm that urls.json is in the same directory as capture.js, or change inputPath to its actual location. The script resolves the path relative to the script, not the shell’s current directory.
  • “Invalid JSON”: check commas, quotation marks, brackets, and that the file contains JSON rather than JavaScript syntax or comments.
  • Expected a JSON object with a “urls” array: use the stated object format, not a top-level array. Ensure every item in urls is a string.
  • URL skipped as malformed or unsupported: include the scheme, such as https://, and use only HTTP or HTTPS URLs. Blank entries are skipped.
  • Navigation timeout: the host may be slow, unresponsive, or continuously active. Check whether the page is reachable, set a timeout suited to the sites, and consider domcontentloaded followed by a page-specific selector rather than waiting for network idleness.
  • Screenshot is blank or missing late content: choose a better readiness condition and confirm the selector exists on that page. A navigation event alone does not guarantee that client-rendered data, fonts, or remote assets are ready.
  • Browser launch fails: let Puppeteer install its supported Chrome for Testing browser, or, with puppeteer-core, provide a valid executablePath or channel. Arbitrary browser versions are not guaranteed compatible.
  • Two captures overwrite one another: retain the index in the output filename or use a unique identifier for each input. Do not use an unmodified URL path as a filename.
  • Output directory is missing: the script creates screenshots recursively. If it still fails, check filesystem permissions and available disk space.

Or skip the browser setup

If you do not want to install and maintain Puppeteer and a local browser, ScreenshotNeo can return a screenshot from one GET request. Its API accepts image or PDF capture requests, and the call below saves a WebP response. See the ScreenshotNeo documentation for API parameters and response details.

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
  • Cookie and consent banners are accepted before capture; the service removes more than 60 known consent platforms, newsletter popups, and chat widgets. Each of these steps can be turned off.
  • Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed. Responses include X-Page-Verdict and X-Billed headers.
  • An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents, including 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. Every feature is available on every plan.

Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.

Best Value
Canon Canoscan Lide 300 Scanner (PDF, AUTOSCAN, Copy, Send)
  • Scanner type: Document
  • Connectivity technology: USB
  • With Auto Scan Mode, the scanner automatically detects what you're scanning
  • Digitize documents and images

Frequently Asked Questions

Does the JSON file have to use a property named `urls`?

No. That is the input shape this example validates. Change `readUrls()` to match your own JSON structure.

Can I save a PDF instead of an image with Puppeteer?

Yes. Puppeteer has a separate `page.pdf()` method for PDF output; its options and behavior differ from screenshot options.

Can the script capture the same URL more than once?

Yes. Each valid array entry is processed independently and receives an index-based filename.

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

Quick Recap

SaleBestseller No. 3
Canon imageFORMULA R10 - Portable Document Scanner, USB Powered, Duplex Scanning, Document Feeder, Easy Setup, Convenient, Perfect for Mobile Users, White
Canon imageFORMULA R10 - Portable Document Scanner, USB Powered, Duplex Scanning, Document Feeder, Easy Setup, Convenient, Perfect for Mobile Users, White
BROAD COMPATIBILITY – Works with both Windows and Mac devices, be it laptop or computer; This product is not intended for scanning photographs on photo paper / photographic media
$153.00
Bestseller No. 4
IRIScan Express 4 Black Compact Portable USB Simplex Document Scanner, 8 PPM for Contracts, Invoices and Business Cards, Compatible with Windows, Readiris PDF Included
IRIScan Express 4 Black Compact Portable USB Simplex Document Scanner, 8 PPM for Contracts, Invoices and Business Cards, Compatible with Windows, Readiris PDF Included
Find our Software here : irislink.com/start; IRIScan Express is only compatible Windows platform and not macintosh
$129.00
Bestseller No. 5
Canon Canoscan Lide 300 Scanner (PDF, AUTOSCAN, Copy, Send)
Canon Canoscan Lide 300 Scanner (PDF, AUTOSCAN, Copy, Send)
Scanner type: Document; Connectivity technology: USB; With Auto Scan Mode, the scanner automatically detects what you're scanning
$75.00

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.