How to take a screenshot of a web page using Node JS (Puppeteer + Chrome)

Let’s get started with the procedure to take a screenshot of a web page using NodeJs.Following is the step by step and easy process which will make our work smooth with the help of Puppeteer,  a Node JS web scrapping library. Puppeteer uses headless chrome browser for the scrapping process Which is one of its advantages.

1.Install the latest version of Node Js

First of all, we need to install the latest version of Node Js. We can run following commands to install the Node Js in the Linux machine.

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

To know more about the installation check out: Node Js Installation

2. Install Puppeteer

After the Nodejs installation, we need to create a new project folder and install Puppeteer, which comes with a recent version of Chromium. We can run the following command to install Puppeteer.

 npm install --save puppeteer 

 

3. Script for Website screenshot

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

 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();

Here is the explanation 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

 

4. Run Script

The final step to take the screenshot is to run the following command, which will create a png file inside the project folder.

 node webscreenshot.js

Sarav Author

Comments

  • David

    (June 19, 2018 - 4:20 pm)

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

  • velvamccormick

    (October 30, 2018 - 7:14 pm)

    Very nice article. I certainly appreciate this website.

    Continue the good work!

Leave a Reply to velvamccormick Cancel reply

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