Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
FREEDOM251

Freedom251 › Blog › JSON

How to Capture Screenshots of URLs from a JSON File with Puppeteer

By Freedom251 Team · · 6 min read

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

Read and validate a JSON file, then use Puppeteer to visit each URL and save a uniquely named screenshot. The example below expects a file named urls.json with a top-level urls array of strings; it processes entries sequentially, waits for network idleness, and continues if one URL fails.

Prepare the JSON input

Create urls.json in your project directory:

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

This shape is an assumption for the script, not a Puppeteer requirement. Each entry should be an absolute HTTP or HTTPS URL. The script checks the JSON structure and URL scheme before opening a browser, and skips invalid entries with a useful message.

As an Amazon Associate I earn from qualifying purchases.

Install Puppeteer and save the script

In a new Node.js project, install Puppeteer, which works best with its downloaded Chrome for Testing browser:

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.
npm init -y
npm install puppeteer

Save the following as capture.js beside urls.json. It reads the file as UTF-8, creates an output directory, and saves one PNG per valid URL. Index-based names prevent URLs with the same hostname from overwriting one another.

#1 Best Overall
Sale
Epson Workforce ES-50 Compact & Lightweight Mobile Document Scanner | For Computers including PC and Mac Receipt and Document Scanner USB Powered
  • 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');

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

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

  if (!data || typeof data !== 'object' || !Array.isArray(data.urls)) {
    throw new Error('Expected a JSON object with a "urls" array.');
  }

  return data.urls.map((value, index) => {
    if (typeof value !== 'string' || value.trim() === '') {
      return { index, error: 'URL must be a non-empty string.' };
    }

    let parsed;
    try {
      parsed = new URL(value.trim());
    } catch {
      return { index, error: 'Not a valid absolute URL.' };
    }

    if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
      return { index, error: 'Only HTTP and HTTPS URLs are supported.' };
    }

    return { index, url: parsed.href, hostname: parsed.hostname };
  });
}

async function main() {
  const inputPath = path.join(__dirname, 'urls.json');
  const outputDir = path.join(__dirname, 'screenshots');
  const entries = await readUrls(inputPath);
  await fs.mkdir(outputDir, { recursive: true });

  let browser;
  const failures = [];

  try {
    browser = await puppeteer.launch();

    for (const entry of entries) {
      if (entry.error) {
        console.error(`Entry ${entry.index + 1}: ${entry.error}`);
        failures.push(entry.index + 1);
        continue;
      }

      // Use a new page per URL so page state does not carry between captures.
      const page = await browser.newPage();
      try {
        await page.setViewport({ width: 1365, height: 900 });
        await page.goto(entry.url, {
          waitUntil: 'networkidle2',
          timeout: 30000,
        });

        const filename = `${String(entry.index + 1).padStart(4, '0')}-${entry.hostname.replace(/[^a-z0-9.-]/gi, '_')}.png`;
        const outputPath = path.join(outputDir, filename);
        await page.screenshot({ path: outputPath });
        console.log(`Saved ${outputPath}`);
      } catch (error) {
        // Avoid echoing the full URL, which may contain credentials or tokens.
        console.error(`Entry ${entry.index + 1} failed (${entry.hostname}): ${error.message}`);
        failures.push(entry.index + 1);
      } finally {
        await page.close();
      }
    }
  } finally {
    if (browser) await browser.close();
  }

  if (failures.length) {
    console.error(`Failed or skipped entries: ${failures.join(', ')}`);
    process.exitCode = 1;
  }
}

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

Run it and find the screenshots

  1. Put urls.json and capture.js in the project directory.
  2. Run node capture.js.
  3. Open the generated screenshots directory. Files are named with a zero-padded input index and hostname, such as 0001-example.com.png.

Sequential processing is deliberate: it is simple and limits simultaneous browser work. The script continues after an individual navigation or capture error, reports failed or skipped entry numbers, closes each page, and closes the browser in a finally block. A failure to read or parse the input, or to launch the browser, stops the run.

Choose when a page is ready

waitUntil: 'networkidle2' follows the readiness choice shown in Puppeteer’s screenshot guide, but it is not proof that every application has finished rendering. Puppeteer’s screenshot guide demonstrates the basic launch, page, navigation, screenshot, and close sequence. The network-idle API resolves after the network is idle for the configured idle period; pages with polling or persistent requests may not reach that condition promptly.

  • Use a navigation event such as domcontentloaded when the initial document is sufficient and you will explicitly wait for application content afterward.
  • Use network idle for pages whose relevant resources settle, while retaining a timeout for pages with long-lived network activity.
  • Wait for a page-specific selector when a known element signals that the content you need has appeared. For example, after navigation, call await page.waitForSelector('[data-report-ready]', { timeout: 15000 }); using a selector that actually exists on your target page.

Client-rendered data, fonts, animations, consent prompts, and remote assets can change what appears between runs. If consistent captures matter, choose an application-specific ready signal and control the viewport and other page state.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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)

Choose viewport, full-page, or clipped output

The script sets a 1365-by-900 viewport and takes a viewport screenshot. Change the viewport dimensions to suit the layout you want to inspect. To capture the full page instead, change the screenshot call to:

await page.screenshot({ path: outputPath, fullPage: true });

Full-page output can be much taller and larger than a viewport capture. Puppeteer’s screenshot options also include type, clip, omitBackground, and quality. The file extension can determine the image type; use a matching extension when changing formats. quality applies to supported lossy formats, not PNG. See the Page.screenshot() API for option details; fullPage defaults to false.

Browser setup and batch-size trade-offs

Managed Chrome

The example uses the puppeteer package and its managed Chrome for Testing download. Puppeteer says this is the browser setup it works best with.

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

Using puppeteer-core

If you use puppeteer-core, configure executablePath or channel when launching. Puppeteer does not guarantee compatibility with arbitrary browser versions; consult the launch API documentation and use a compatible browser installation.

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

Scaling beyond sequential runs

For a larger batch, bounded concurrency can reduce elapsed time, but every active page uses browser and machine resources. No universal safe number of parallel pages is established; measure with your pages and environment, and keep a limit rather than opening a page for every URL at once.

Node’s promise-based readFile reads the entire file into memory. That is convenient for a modest URL list; for unusually large inputs, use a streaming design rather than buffering the complete JSON document. See Node.js file system documentation.

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
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”: Check that urls.json is in the same directory as capture.js, or update inputPath to the right location.
  • “Invalid JSON”: Check commas, quotation marks, braces, and the closing brackets. JSON does not allow comments or trailing commas.
  • Expected a “urls” array: Use the documented example shape, with a top-level object containing urls as an array.
  • Entry skipped: Supply a non-empty absolute URL beginning with http:// or https://.
  • Navigation timeout: The site may be slow or maintain network activity. Increase the timeout if appropriate, use a different navigation readiness event, and wait separately for the content selector you need.
  • Screenshot is blank or incomplete: The page may render important content after navigation. Wait for a meaningful selector or application-specific signal before capturing.
  • Browser launch error: Check that installation completed and the managed browser is available. With puppeteer-core, provide a valid executablePath or channel for a compatible browser.
  • Output file overwritten: Retain the input index in each filename or use an explicit unique ID per entry; a hostname alone may repeat.

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server. A GET request can return a screenshot or PDF; its cleanup can accept cookie and consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture, with each step configurable. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server exposes screenshot and PDF tools for AI agents.

For a URL, make one request (replace YOUR_API_KEY and the target URL):

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

See the ScreenshotNeo API documentation for request parameters and options. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Sign up for free.

Frequently Asked Questions

Does Puppeteer take a full-page screenshot by default?

No. Set fullPage: true in page.screenshot() to request full-page output.

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

Can I capture only part of a page?

Yes. The screenshot options include clip; use the Page.screenshot() API documentation for its supported shape and behavior.

Can a JSON file contain just an array of URLs?

Yes, but this example expects an object with a urls property. Change the validation and mapping to match a top-level array if that is your chosen schema.

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.

JSONNode.jsPuppeteerscreenshotsweb automation

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.