How to take a screenshot of the element with Puppeteer

Posted February 1, 2022 by Dmytro Krasun ‐ 1 min read

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.

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:

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. That’s it.

If you want to check out the complete guide on how to take screenshots with Puppeteer, you are welcome, and have a nice day!