Halloween 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 NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › browser automation

How to Take Batch Screenshots of Indian Government Websites with Playwright

By Freedom251 Team · · 8 min read

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

Use one Playwright browser and a shared browser context, then navigate to each URL in your list and save a uniquely named screenshot. The example below captures full pages sequentially, logs each result, and continues after individual failures. Before running it, check the access rules, terms, and request policies for every target site: those vary by site, and there is no universal permission or safe request rate for Indian government websites.

Before you run a batch

Decide which public pages you need and check the policies for the actual domains. The rules for access, automation, redirects, and request volume cannot be inferred for an unspecified government site. This example makes one navigation at a time; it does not bypass access controls or establish that a target permits automated capture.

As an Amazon Associate I earn from qualifying purchases.

  • Use URLs you are authorized to access, and keep the batch limited to the pages you need.
  • Start sequentially. For larger batches, consider bounded concurrency only after checking site policies and your machine’s resource limits.
  • Choose a capture scope—viewport, full page, one element, or a fixed rectangle—based on what the record needs to show.

Set up Playwright

Use a current Node.js installation and install Playwright in a project directory. The commands below install the Playwright package and its Chromium browser:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. npm init -y
  2. npm install playwright
  3. npx playwright install chromium

Save the script below as batch-screenshots.mjs and run it with node batch-screenshots.mjs. It creates the output directory if needed, captures each URL in order, writes a JSON-lines log, and closes pages and browser resources even when a capture fails.

Capture a list of URLs

import { chromium } from 'playwright';
import { appendFile, mkdir } from 'node:fs/promises';
import path from 'node:path';

const urls = [
  'https://example.gov.in/',
  'https://example.gov.in/about',
];
const outputDir = path.resolve('screenshots');
const logPath = path.join(outputDir, 'index.jsonl');

await mkdir(outputDir, { recursive: true });
const browser = await chromium.launch();
const context = await browser.newContext({
  viewport: { width: 1440, height: 1000 },
  locale: 'en-IN',
});

try {
  for (const [index, url] of urls.entries()) {
    const page = await context.newPage();
    const filename = `${String(index + 1).padStart(3, '0')}.png`;
    const outputPath = path.join(outputDir, filename);
    const record = {
      inputUrl: url,
      capturedAt: new Date().toISOString(),
      outputPath,
    };

    try {
      const response = await page.goto(url, {
        waitUntil: 'domcontentloaded',
        timeout: 30_000,
      });

      // Replace with a site-specific locator/readiness check if needed.
      await page.screenshot({ path: outputPath, fullPage: true });

      record.finalUrl = page.url();
      record.httpStatus = response?.status() ?? null;
      record.outcome = 'captured';
      console.log(record);
    } catch (error) {
      record.finalUrl = page.url();
      record.outcome = 'failed';
      record.error = String(error);
      console.error(record);
    } finally {
      await appendFile(logPath, `${JSON.stringify(record)}n`);
      await page.close();
    }
  }
} finally {
  await context.close();
  await browser.close();
}

The numeric filename is unique within this run, even when two URLs have the same path or normalize to similar names. The log associates each filename with the input URL, final URL after any redirects, timestamp, HTTP status when available, and outcome. If you rerun the script into the same directory, files with matching numbers are overwritten; use a fresh output directory or add a run-specific subdirectory if you need to preserve earlier batches.

Choose what each screenshot should contain

Viewport capture

Omit fullPage to capture only the visible viewport:

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

This is useful for recording the initial visible state. Keep viewport dimensions fixed when comparing pages or runs.

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

Full-page capture

Set fullPage: true to capture the full scrollable page:

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

Long pages can produce unusually tall, large images. There is no universal page-length threshold at which full-page capture becomes unsuitable, so consider the output’s use and storage needs.

Element capture

Use a locator when only one component matters. Wait for the component to exist or become visible if the page renders it dynamically:

const panel = page.locator('main');
await panel.waitFor({ state: 'visible', timeout: 10_000 });
await panel.screenshot({ path: outputPath });

Replace main with a selector that identifies the intended component on the target site.

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

Fixed rectangular region

Use clip when the record should cover a specific rectangle in the page viewport:

await page.screenshot({
  path: outputPath,
  clip: { x: 0, y: 0, width: 900, height: 600 },
});

Set the coordinates and dimensions to the area you need. A clipped capture is not a substitute for a full-page record.

Format, scale, and repeatability controls

Playwright supports PNG, JPEG, and WebP output through screenshot options; select the format and, where supported, quality to balance fidelity and file size. The file extension should match the selected format. scale: 'css' produces one image pixel per CSS pixel; device scale preserves device-pixel sizing. Screenshot options also include animation handling, caret behavior, masks, and injected styles. Use these only when they serve the purpose of the record, and document any changes that alter what the page shows.

Wait for the page that matters

The example uses waitUntil: 'domcontentloaded' as a starting point, not a guarantee that all visible content has settled. A client-rendered page, delayed component, or lazy-loaded image may need a site-specific readiness check after navigation. For example, if the main heading is the signal that the page is ready:

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.
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30_000 });
await page.locator('h1').waitFor({ state: 'visible', timeout: 10_000 });
await page.screenshot({ path: outputPath, fullPage: true });

Choose a selector that corresponds to meaningful content on the target page; a generic delay can make a script slower without proving the page is ready. Playwright offers load, domcontentloaded, networkidle, and commit navigation conditions. Its Page API discourages treating networkidle as a universal readiness strategy; use an assertion or page-specific condition to determine whether the content you need is present.

Manage state, concurrency, and output integrity

Shared or isolated browser state

The sample uses one browser context for the batch, which shares context-level settings such as viewport and locale across its pages. Contexts also hold session state, so cookies or storage set while visiting one page may affect later pages in that context. If targets must not share session state, create a separate non-persistent context for each isolation group and close it when finished.

Sequential versus bounded concurrency

Sequential navigation is straightforward and avoids an unbounded burst of requests. The example opens and closes one page at a time. If you add parallel workers for a larger list, set an explicit small concurrency limit rather than launching a page for every URL at once. The appropriate request rate depends on each target’s rules and capacity; no universal safe rate is established for Indian government sites.

Stable comparisons and useful records

Browser output can vary with operating system, browser version, settings, hardware, power source, and headless mode. For repeat comparisons, pin the runtime where practical and keep viewport, device scale, locale, and color scheme consistent. Also account for dates, rotating content, animations, banners, and personalization. A screenshot records what that particular setup rendered at that time; it is not a canonical rendering for every visitor.

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

For responsive review, run deliberate batches at each viewport size and include the dimensions in the log or output directory name. Keep the capture options with the files so a later comparison can distinguish page changes from setup changes.

What screenshots can and cannot establish

The official Guidelines for Indian Government Websites portal identifies GIGW 3.0 and provides resources related to accessibility and mobile friendliness: GIGW portal. Its accessibility guidance says meaningful explanatory text equivalents should be provided for images and other non-text content, and describes evaluation using manual checks as well as accessibility tools: GIGW accessibility guidance.

A screenshot can document rendered appearance, but it cannot by itself establish accessibility or GIGW conformance. Those require evaluation beyond visual appearance alone.

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

Troubleshooting

Navigation times out

Check whether the URL is correct and reachable from the machine running the script. The site may be slow, redirecting, or waiting on resources; inspect the recorded error and final URL. Increase the timeout only when a longer wait is justified, and prefer a meaningful readiness condition over waiting indefinitely.

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.

The screenshot is blank or missing content

domcontentloaded means the initial document has been parsed; it does not guarantee that client-rendered content or delayed assets are ready. Wait for a site-specific locator that represents the content you need. If the page relies on lazy loading, determine whether scrolling or another page interaction is needed before capture, and keep that interaction consistent between runs.

Two inputs overwrite or confuse output files

Do not derive filenames by simply replacing URL punctuation: distinct URLs can collapse to the same sanitized name. The sample avoids that collision within a run by assigning sequential numbers and recording the source URL in index.jsonl. For repeatable names across runs, use a collision-resistant identifier and retain the URL-to-file index.

Images differ between runs

Check the browser/runtime version, operating system, headless setting, viewport, device scale, locale, and color scheme. Then identify dynamic page content such as dates, rotating panels, animations, consent banners, or personalization. Screenshot controls such as animation handling, masks, and styles can reduce known variation, but should not conceal evidence relevant to the purpose of the capture.

One bad URL stops the entire job

Keep navigation and screenshot errors inside the per-URL try block, as shown. The script records the failed input and continues to the next page; the outer finally still closes browser resources.

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

Or skip the browser setup

ScreenshotNeo offers a screenshot API and MCP server for developers. A single GET request can return a screenshot or PDF; the API accepts options for full-page and element capture, viewport and device settings, waiting, output format, and other capture controls. See the ScreenshotNeo site and API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.gov.in/about -o shot.webp

Replace the example URL with a page you are authorized to capture. Cookie banners are accepted and removed before the shot, along with known newsletter popups and chat widgets; each cleanup step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies page verdict and billing status in headers. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients. The Free plan includes 1,000 screenshots a month without a card; paid plans start at $5 for 3,000 shots. Check the target site’s policies before submitting URLs through an API as well. Sign up for 1,000 free screenshots a month with no card.

Frequently Asked Questions

How do I capture several viewport sizes for the same government page?

Run a deliberate capture pass for each viewport and record its width and height alongside each output, so images from different responsive layouts are not confused.

Does a successful screenshot prove the page is accessible?

No. It documents appearance; accessibility needs evaluation beyond a screenshot, including the relevant manual and tool-assisted checks.

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

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.

browser automationIndian government websitesNode.jsPlaywrightweb screenshots

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
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

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.