How can I take screenshots using Puppeteer?

Puppeteer is a Node.js library that provides a high-level API to control Google Chrome or Chromium over the DevTools Protocol. Puppeteer runs headless by default but can be configured to run full (non-headless) Chrome or Chromium.

Puppeteer's API is very versatile and allows us to take screenshots of web pages, among many other things.

Here's how you can take screenshots using Puppeteer:

Installation

First, you need to install Puppeteer. Since Puppeteer is a Node.js library, you can install it using npm:

npm i puppeteer

Taking Screenshots

To take a screenshot of a webpage, you need to launch a browser instance, open a new page, navigate to the desired URL, and then use the screenshot function.

Here is a simple example:

const puppeteer = require('puppeteer');

async function takeScreenshot() {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://example.com');
    await page.screenshot({path: 'example.png'});
    await browser.close();
}

takeScreenshot();

In this example, the puppeteer.launch() function starts a new browser instance. The browser.newPage() function opens a new tab in the browser. The page.goto('https://example.com') function navigates to the URL specified. The page.screenshot({path: 'example.png'}) function takes a screenshot of the page and saves it as 'example.png'. The browser.close() function closes the browser instance.

You can customize your screenshots by passing options to the screenshot() function. For instance, you can change the format of the screenshot to jpeg and set the quality to 80% like this:

await page.screenshot({path: 'example.jpeg', type: 'jpeg', quality: 80});

You can also capture a full page screenshot by setting the fullPage option to true:

await page.screenshot({path: 'example.png', fullPage: true});

For more details, you can refer to the Puppeteer API documentation.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon