How to do a screenshot using Puppeteer

By

Learn how to take a screenshot with Puppeteer using the page.screenshot() method, set a path to save the file, and add the fullPage option for the whole page.

~~~

To take a screenshot with Puppeteer you call the screenshot() method on a page object, passing the path where you want the image saved.

Here’s a complete script that captures a website:

const puppeteer = require('puppeteer')

const main = async () => {
  const browser = await puppeteer.launch()
  const page = await browser.newPage()
  await page.goto('https://flaviocopes.com')
  await page.screenshot({ path: 'screenshot.jpg' })
  await browser.close()
}

main()

Run it, and you’ll find screenshot.jpg in the folder, showing the page exactly as the headless Chrome browser rendered it.

The file extension in path decides the image format. Use .png for PNG, .jpg or .jpeg for JPEG, .webp for WebP.

How do you capture the whole page?

By default the screenshot only captures the visible viewport. Everything below the fold is cut off.

Add the fullPage option to capture the entire page, scrolling included:

await page.screenshot({
  path: 'screenshot.jpg',
  fullPage: true,
})

If instead you want a larger viewport, set it before navigating:

await page.setViewport({ width: 1280, height: 800 })

This changes what “visible” means, so a plain screenshot captures a bigger area.

Getting the image data instead of a file

If you omit path, nothing gets written to disk. screenshot() returns the image data, and you decide what to do with it: upload it to storage, send it back in an HTTP response, attach it to an email.

const image = await page.screenshot()

Be careful with timing

A common problem: the screenshot shows a half-loaded page, with missing images or empty spots where content should be. It happens because page.goto() can resolve while some resources are still loading in the background.

Tell Puppeteer to wait until network activity settles:

await page.goto('https://flaviocopes.com', {
  waitUntil: 'networkidle2',
})

With networkidle2, navigation is considered done when no more than 2 network connections have been active for at least half a second. For most pages, that means everything visible has arrived, and the screenshot looks like what a real visitor sees.

Also see my full Puppeteer tutorial

Tagged: Node.js · All topics
~~~

Related posts about node: