How to take a screenshot of the element with Puppeteer

Puppeteer allows you to automate everything you can do in the browser manually and even more. You can take screenshots of the entire page and the specific elements.

1 min read

Written by

Dmytro Krasun

Updated on

Puppeteer allows you to automate everything you can do in the browser manually and even more. You can take screenshots of the entire page and the specific elements.

Make sure you installed the puppeteer library first:

Terminal window
npm i puppeteer

Then you can import the library and take a screenshot of any desired element:

'use strict';
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
try {
const page = await browser.newPage();
await page.goto('https://example.com');
const selector = 'body > div:first-child';
await page.waitForSelector(selector);
const element = await page.$(selector);
await element.screenshot({
path: 'example.com.png',
});
} catch (e) {
console.log(e)
} finally {
await browser.close();
}
})();

It is essential to wait until the selector is ready and rendered. Otherwise, you can miss it and take a screenshot of nothing. After the element is ready, you need to find it (select it) and then call the screenshot() method.

In our screenshot API, you can take the screenshot of the element by specifying the selector parameter.

If you want to check out the complete guide on how to take screenshots with Puppeteer, you are welcome.

Read more posts

Interviews, tips, guides, industry best practices, and news.

View all posts

How to build a Programmatic SEO site with automated website screenshots using ScreenshotOne, Airtable, and Launchman

Programmatic SEO is a great growth hacking strategy where you create a large number of content pages that rank for long-tailed keywords on Google.

Read more

How to screenshot websites in Next.js

There 3 simple ways to render website screenshots in Next.js—using Puppeteer, Cloudflare Browser Rendering, and a screenshot API like ScreenshotOne or similar.

Read more

Why and how to choose a screenshot API

You don't need a screenshot API if it is a one-off task for you and you can use some library for screenshotting.

Read more

Automate website screenshots

Exhaustive documentation, ready SDKs, no-code tools, and other automation to help you render website screenshots and outsource all the boring work related to that to us.