User Agents

How to Build a Screenshot Script for Browser Automation

Building a screenshot script for browser automation means writing code that launches a browser, navigates to a page, and saves an image of what the browser renders. This is useful for visual regression testing, monitoring dashboards, generating thumbnails, or capturing evidence of a page state. You do not need a full test framework to start; a single script and a browser automation library are enough. The main prerequisites are a working programming environment (Node.js or Python are common choices) and a browser automation tool such as Playwright, Puppeteer, or Selenium. You should also have permission to access and capture the pages you target, and you should respect the site's terms of service and any applicable rules about automated access.

What You'll Need

  • A code editor and a terminal.
  • Node.js (for Playwright or Puppeteer) or Python (for Playwright or Selenium).
  • A browser automation library installed in your project.
  • The browser binaries that the library manages (Playwright and Puppeteer can download them for you).
  • A target URL you are allowed to capture, and a place to save image files.

Step-by-Step

  1. Choose your automation library. Playwright and Puppeteer both control Chromium and offer simple screenshot APIs. Playwright also supports Firefox and WebKit and has built-in waiting helpers. Selenium is a good choice if you already use it for testing. Pick one and stick with it for the project so you do not mix APIs.
  2. Set up a project folder. Create a new directory and initialise it. For Node.js, run npm init -y. For Python, create a virtual environment so the library does not conflict with system packages. Keep the script and its output folder inside the project.
  3. Install the library. For Node.js, install Playwright with npm i playwright and then run npx playwright install to download browser binaries. For Puppeteer, npm i puppeteer downloads a compatible Chromium by default. For Python, pip install playwright followed by playwright install. These commands fetch the browser builds the library expects, which avoids version mismatches.
  4. Write the launch and navigation code. Import the library, launch a browser instance, create a new page, and navigate to the URL. Use the library's waiting method so the script does not capture a blank page. In Playwright, page.goto(url, { waitUntil: 'networkidle' }) waits for network activity to settle; in Puppeteer, page.goto(url, { waitUntil: 'networkidle0' }) does the same. Selenium users should use explicit waits for a specific element rather than a fixed sleep.
  5. Set the viewport size. Screenshots depend on the viewport. Set a consistent width and height before navigation so captures are repeatable. A common desktop size is 1280 by 800 or 1440 by 900. If you need mobile layouts, set a mobile viewport and a matching user agent string from the library's device presets.
  6. Take the screenshot. Use the page's screenshot method and provide a file path. Decide between a viewport screenshot (only the visible area) and a full-page screenshot (the entire scrollable page). Full-page captures are larger and can be slow on long pages, but they are better for visual comparisons. Save with a descriptive filename that includes a timestamp so runs do not overwrite each other.
  7. Handle dynamic content. Many pages load content after the initial HTML. Wait for a specific selector that indicates the page is ready, or wait for a network idle state. If a cookie banner or modal blocks the content, dismiss it with a click before capturing. Avoid arbitrary sleeps where possible because they make the script slow and unreliable.
  8. Close the browser cleanly. Always close the browser at the end, even if an error occurs. Use a try/finally block or the library's context manager so the process does not leave orphaned browser processes running. Clean shutdown also flushes any pending writes to disk.
  9. Add error handling and logging. Wrap navigation and capture in error handling. Log the URL, the timestamp, and the output path. If a selector wait times out, log which selector failed. This makes failures diagnosable without rerunning the script blindly.
  10. Run and verify. Execute the script from the terminal. Open the saved image and confirm it shows the expected page, not an error page or a blank canvas. Check the image dimensions and file size. If the image is blank, the capture likely happened before rendering finished.
  11. Schedule or integrate. Once the script works, you can run it on a schedule with a task runner or cron, or call it from a test suite. Keep the output folder organised by date and page so you can compare runs later.

Common Mistakes

  • Capturing too early. Taking a screenshot immediately after navigation often produces a blank or partially rendered image. Wait for a specific element or network idle.
  • Ignoring the viewport. Relying on the default viewport produces inconsistent layouts. Set width and height explicitly.
  • Using fixed sleeps everywhere. Long sleeps make scripts slow and still fail when a page is slower than expected. Prefer event-based waits.
  • Forgetting to close the browser. Leftover browser processes consume memory and can lock files. Always close in a finally block.
  • Overwriting files. A fixed filename means each run replaces the last. Include a timestamp or run identifier.
  • Assuming full-page works everywhere. Some pages use fixed or sticky elements that repeat or overlap in full-page captures. Check the output and fall back to viewport captures if needed.

Tips

  • Use headless mode for speed and CI environments, but run headed mode occasionally to see what the browser actually does.
  • Set a consistent device scale factor so images are comparable across machines.
  • Disable animations and transitions before capture where the library supports it, to avoid mid-animation frames.
  • Store screenshots in a dedicated folder and clean old files on a schedule to avoid filling disk.
  • Capture the page title or a visible heading in the log alongside the image path for easier auditing.
  • Respect rate limits and terms of service; do not hammer a site with repeated captures.

Troubleshooting

If the screenshot is blank, the page likely had not rendered. Add a wait for a visible selector that only appears after content loads, and confirm the selector is correct by checking the page source. If navigation times out, the site may be slow or blocking automated browsers; check whether the page loads manually and whether the library's user agent is being rejected. If the browser fails to launch, the browser binaries may be missing or mismatched; reinstall them with the library's install command. If the image is cut off, the viewport is too small for the content or the page uses lazy loading; increase the viewport or scroll to trigger loading before capture. If fonts or images are missing, the capture happened before those resources finished loading; wait for network idle or for the specific resource. If the script works locally but fails on a server, check that the server has the required system libraries for the browser and enough memory; headless browsers need more than a minimal container often provides. If files are not written, check the output path is absolute or correct relative to the working directory and that the process has write permission.

Frequently Asked Questions

Do I need a full testing framework to take screenshots?

No. A single script using Playwright, Puppeteer, or Selenium can launch a browser, navigate, and save an image. Frameworks help with organisation and assertions but are not required.

What is the difference between a viewport and a full-page screenshot?

A viewport screenshot captures only the visible area at the current scroll position. A full-page screenshot captures the entire scrollable page, which is larger and can be slower but shows all content.

Why is my screenshot blank?

The most common cause is capturing before the page finishes rendering. Wait for a specific element or for network idle, and dismiss any overlays that block content.

Can I take screenshots of pages that require login?

Yes, if you have permission to access the account. Log in through the automation script or reuse a saved session state, then navigate to the page and capture. Do not use this to access accounts or data you are not authorised to view.

How do I keep screenshots from overwriting each other?

Include a timestamp or unique run identifier in the filename, and save each run to its own folder or with a date prefix.

Does headless mode change how the page looks?

It can. Some sites detect headless browsers or render differently without a visible window. If appearance matters, compare headless and headed output and adjust the viewport, user agent, or rendering settings as needed.