Take a screenshot of web page using Node JS (Puppeteer + Chrome)

Here we have provided the step by step process to take a screenshot of web page using Node JS. For that, we have used Puppeteer. It is a Node JS web scrapping library. Puppeteer uses headless chrome browser for the scrapping process Which is one of its advantages.

 
The following are the steps

Install latest version of Node Js

Need to install the latest version of Node Js 8+. Run the following commands to install the Node Js in Linux System. To know more about the installation check out: Node Js Installation

 sudo apt-get update
 sudo apt-get install nodejs
 sudo apt-get install npm 

 

Install Puppeteer

After Node installation, create a new project folder and install Puppeteer. Puppeteer comes with a recent version of Chromium. Run the following command to install Puppeteer.

 npm install --save puppeteer 

 

Script for Website screenshot

The following is the sample code for taking the screenshot of our website `mytypings.com`. To get started, create a file `webscreenshot.js` inside that project folder and copy paste the following code.

 const puppeteer = require('puppeteer');
 async function getScreenShot() {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://mytypings.com');
  await page.setViewport({width: 1000, height: 500})
  await page.screenshot({path: 'mytypings.png'});
  await browser.close();
 }
 getScreenShot();

The following are brief about the code

  • Line 1: Including the puppeteer library
  • Line 4: Launching the chrome browser with headless mode
  • Line 5: Adding a new page in the browser
  • Line 6: Opening the website url
  • Line 7: Setting the view point to the browser
  • Line 8: Taking the screen shot of the site
  • Line 10: Closing the browser

 

Run Script

Run the following command to take the screen shot. The result PNG file will be created in that project folder.

 node webscreenshot.js

Sarav Author

Comments

  • David

    (June 19, 2023 - 4:20 pm)

    This is interesting article for me..
    I added your site into my bookmarks.
    Keep up good work! Excited for future updates!

Leave a Reply

Your email address will not be published. Required fields are marked *