How to render and save a webpage as a PNG file in Puppeteer?

To render and save a webpage as a PNG file using Puppeteer, you can use the following code snippet:

const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://www.example.com'); await page.screenshot({ path: 'example.png', fullPage: true }); await browser.close(); })();

In this code snippet:

  • puppeteer.launch() launches a new browser instance
  • browser.newPage() creates a new page in the browser
  • page.goto() navigates to the specified webpage
  • page.screenshot() takes a screenshot of the page and saves it as a PNG file with the specified path
  • browser.close() closes the browser instance

You can customize the screenshot by specifying options like fullPage to capture the entire page, or specifying the clip area via the clip option.