Web scraping
How to take screenshots with Puppeteer
One method, page.screenshot, covers most needs, and element handles add a second for precise crops. This guide shows each form and how screenshots turn a vague scraping failure into something you can see.
The basic call
A screenshot in Puppeteer is one awaited call on a page. By default it captures the current viewport as a PNG. Everything else, full length captures, crops, formats and quality, is an option on that same call. The examples use ES modules on a current Node.js release; install the library with npm install puppeteer, which also downloads a compatible browser build.
import pptr from "puppeteer";
const chromium = await pptr.launch({ headless: true });
const tab = await chromium.newPage();
await tab.setViewport({ width: 1280, height: 800, deviceScaleFactor: 1 });
await tab.goto("https://example.com/", { waitUntil: "networkidle2" });
await tab.screenshot({ path: "viewport.png" });
await chromium.close();
The viewport size decides what "the screen" is, so set it deliberately. Responsive sites render a different layout at 390 pixels than at 1280, and a screenshot at the wrong width documents a page your users never see. Raise deviceScaleFactor to 2 when you need sharp text for a report, at the cost of four times the pixels.
Capture the whole page
Add fullPage: true and Puppeteer measures the document height and captures all of it in one image. This is the right tool for archiving a page or comparing layouts between deployments.
await tab.screenshot({
path: "archive/landing-full.jpg",
fullPage: true,
type: "jpeg",
quality: 72,
});
Two things trip people up. First, pages that load content as you scroll only contain the first screen at capture time; scroll to the bottom in a short loop, wait for the network to calm down, then capture. Second, elements with fixed positioning, such as sticky headers and cookie bars, can appear once at the top or repeat depending on the page's CSS. Hide them for clean archives with tab.addStyleTag({ content: ".cookie-bar { display: none !important; }" }) before the call.
Format and size
PNG is lossless and best for text, diagrams and pixel comparisons. JPEG and WebP are much smaller for photos and long pages; set quality between roughly 60 and 85 for a good balance. Very tall pages can hit image dimension limits in the browser, so for endless feeds capture a fixed number of screens instead of the entire document.
Capture a single element
To capture one part of the page, get an element handle and call screenshot on it. Puppeteer scrolls the element into view and crops to its bounding box.
const chart = await tab.waitForSelector("#price-history", { visible: true });
await chart.screenshot({ path: "price-history.png" });
const rows = await tab.$$("table.results tr");
for (const [n, row] of rows.slice(0, 5).entries()) {
await row.screenshot({ path: `row-${n}.png` });
}
Wait for the element to be visible, not merely present, or you may capture an empty box while a chart is still drawing. If an element animates in, add a short wait after it appears, or disable animations by injecting * { animation: none !important; transition: none !important; } with a style tag.
Capture a clipped region
The clip option captures any rectangle, in page coordinates, whether or not it lines up with an element. Combine it with an element's bounding box when you want some padding around it.
const box = await (await tab.$("form#signup")).boundingBox();
const pad = 16;
await tab.screenshot({
path: "signup-area.png",
clip: { x: Math.max(box.x - pad, 0), y: Math.max(box.y - pad, 0),
width: box.width + pad * 2, height: box.height + pad * 2 },
});
Bounding boxes are relative to the viewport at the moment you read them, so read the box and take the screenshot without scrolling in between. When the region is lower on the page than the viewport reaches, either scroll it into view first or add captureBeyondViewport: true so the browser renders outside the visible area.
Use screenshots to debug challenges
When a scraper suddenly returns empty data, the cause is often visible in a single frame: a consent wall, a login redirect, a challenge page or a CAPTCHA widget. Logs show you a status code; a screenshot shows you what the site actually served. Capture one automatically whenever your extraction comes back empty.
async function snapshotOnMiss(page, label) {
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
const base = `debug/${label}-${stamp}`;
await page.screenshot({ path: `${base}.png`, fullPage: true });
await fs.promises.writeFile(`${base}.html`, await page.content());
const marks = await page.evaluate(() => ({
title: document.title,
turnstile: !!document.querySelector(".cf-turnstile, iframe[src*='challenges.cloudflare.com']"),
recaptcha: !!document.querySelector("iframe[src*='recaptcha']"),
}));
console.log(label, marks);
}
This helper needs import fs from "node:fs"; at the top of the module. Saving the HTML next to the image matters, because the image tells you what kind of page it was and the HTML gives you the site key and form fields you need to handle it. The guide to identifying Cloudflare protection shows how to tell a Turnstile widget from a full-page challenge in those files.
Screenshots in headless versus headed runs
If a page looks fine when you watch it in a headed browser but the headless screenshot shows a challenge, the difference itself is the clue. The site is treating the headless run differently, usually because of fingerprint or pacing signals rather than anything in your code. Our article on why a site thinks you are a bot lists the usual suspects.
Screenshots as CAPTCHA input
An element screenshot is also the simplest way to send an image CAPTCHA to a solver. Ask for encoding: "base64" and Puppeteer returns a string instead of writing a file, which is exactly what an Image to Text task expects in its body field.
const pic = await tab.$("img#captcha-image");
const encoded = await pic.screenshot({ encoding: "base64" });
const made = await fetch("https://gatesolver.com/createTask", {
method: "POST",
headers: { Accept: "application/json", "Content-Type": "application/json" },
body: JSON.stringify({ clientKey: "YOUR_API_KEY",
task: { type: "ImageToTextTask", body: encoded } }),
}).then((reply) => reply.json());
console.log("task", made.taskId);
Poll /getTaskResult about once a second, since image tasks finish quickly, then type solution.text into the input exactly as returned. Capturing the rendered element instead of downloading the image URL avoids a second request that might return a different picture. The same base64 approach feeds grid images to reCAPTCHA Image Classification tasks. Image tasks cost $0.28 per 1,000 and are charged only when solved.
Keep screenshot output under control
Screenshots add up fast on a long crawl. Write them only on failures or for a small sample of successes, name files with a label and timestamp, and clean old debug folders on a schedule. On servers, store them where your monitoring can link to them, so the next time a crawl breaks, the person on call can open one image and see the cause.
Common questions
Why is my full page screenshot cut off?
Content that loads on scroll was not there yet. Scroll to the bottom, wait for network activity to settle, then capture again.
Can Puppeteer screenshot an element inside an iframe?
Yes. Get the frame with page.frames() or contentFrame() on the iframe handle, query the element inside it, and call screenshot on that handle.
Which format gives the smallest files?
JPEG or WebP with a quality around 70 is usually far smaller than PNG for pages with photos. Keep PNG for text and pixel comparisons.
Do screenshots slow down scraping a lot?
Viewport captures are fast, full page captures of long documents are slower and memory hungry. Take them only when you need them.
Can I send a screenshot straight to an image CAPTCHA task?
Yes. Use encoding base64 on the element screenshot and pass the string as the body field of an ImageToTextTask, without a data URL prefix.
Keep reading
- Web scraping with PuppeteerPuppeteer scraping beyond the basics: picking the right navigation wait, bulk extraction with $$eval, blocking heavy requests and capturing JSON.
- PuppeteerOne Puppeteer client for three jobs: the reCAPTCHA v2 checkbox, v3 scores tied to an action, and text image CAPTCHAs.
- How do I debug Puppeteer scripts?Run headful with slowMo, forward page console logs, take screenshots on failure and log network responses.
- Image to Text solver$0.28 per 1,000 tasks, answers under 1 seconds.