Puppeteer - Capture Screenshot



We can capture screenshots while working on automation tests developed in Puppeteer using the screenshot method. A screenshot is generally captured if we encounter an application error, a failure in a test case, and so on.

Syntax

The syntax to capture screenshot in Puppeteer is as follows −

await page.screenshot({
   path: 'tutorialspoint.png'
})

Here, the path where the screenshot is to be saved is passed as a parameter to the method. With this, only the viewable part of the web page shall be captured. To capture the full page screenshot, we have to pass another parameter called the fullPage and set its value to true.

Syntax

The syntax is as follows −

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

Let us capture the screenshot of the below page −

Screenshot

To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as follows −

Step 1 − Create a new file within the directory where the node_modules folder is created (location where the Puppeteer and Puppeteer core have been installed).

The details on Puppeteer installation is discussed in the Chapter of Puppeteer Installation.

Right-click on the folder where the node_modules folder is created, then click on the New file button.

Node Modules

Step 2 − Enter a filename, say testcase1.js.

Testcase1.JS

Step 3 − Add the below code within the testcase1.js file created.

//adding Puppeteer library
const pt = require('puppeteer');
pt.launch().then(async browser => {
   //browser new page
   const p = await browser.newPage();
   //set viewpoint of browser page
   await p.setViewport({ width: 1000, height: 500 })
   //launch URL
   await p.goto('https://www.tutorialspoint.com/index.htm')
   //capture screenshot
   await p.screenshot({
      path: 'tutorialspoint.png'
   });
   //browser close
   await browser.close()
})

Step 4 − Execute the code with the command given below −

node <filename>

So in our example, we shall run the following command −

node testcase1.js
Launched in the Browser

After the command has been successfully executed, a new file called the tutorialspoint.png gets created within the page directory. It contains the captured screenshot of the page launched in the browser.

Advertisements