Using puppeteer to Capture Screenshot of a Website
puppeteer is a tools created by Google to control the chrome/Chromium browser by script. It is useful for automatic testing website, or use it to control a headless browser. To use puppeteer to capture screenshot of a site, do:
- Install node.js
- cd to a directory you like
- install puppeteer by
npm i puppeteer
- write a Javascript code
const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto("https://www.google.com", {waitUntil: 'networkidle0'}); //await page.waitForTimeout(1000) await page.screenshot({ path: 'example.png' }); await browser.close(); })();networkidle0the code will wait 500ms after all network activity is done. If the site has some javascript animation, you might need to wait more by using the commentted outwaitForTimeoutcode - run the code by using node. Assume the code name example.js. You do
node example.js
in the terminal.
- It will take around 10 seconds, more or less depends on the complexity of the site, and you will see a file call example.png created by it.
Additional Information
Config the width, height of the screen shot
Add defaultViewport in the code like:
const browser = await puppeteer.launch({
defaultViewport: {width: 1920, height: 1080}
});