Capturing Screenshots with Puppeteer and Node.js: A Step-by-Step Guide
Capturing Screenshots with Puppeteer and Node.js: A Step-by-Step Guide
Puppeteer is a Node.js library developed by the Chrome team, which provides a high-level API to control headless Chrome or Chromium browsers over the DevTools Protocol. It enables developers to automate tasks such as generating screenshots or PDFs of web pages, crawling websites for SEO purposes, testing the performance of web applications, and more. In this blog post, we will explore how to capture screenshots of web pages using Puppeteer and Node.js.
Prerequisites
Before we begin, ensure that you have Node.js installed on your machine. You can download it from the official website: https://nodejs.org/
Now, let's create a new folder for our project and initialize it with npm init. This will create a package.json file to manage our project's dependencies.
Next, we'll install Puppeteer with the following command:
npm install puppeteer
With Puppeteer installed, let's dive into the code example.
How to capture screenshots with Puppeteer and Node.js
import puppeteer from 'puppeteer';
import { join } from 'path';
const OUT = process.env.OUT;
const websites = [
{
name: 'mailslurp',
srcs: [{
name: 'landing',
href: 'https://www.mailslurp.com/'
},{
name: 'pricing',
href: 'https://www.mailslurp.com/pricing'
}]
},
];
(async () => {
const browser = await puppeteer.launch({
headless: "new",
defaultViewport: {
height: 1400,
width: 1024
}
});
await Promise.all(websites.map(async website => {
console.log(`Process ${website.name}`)
const page = await browser.newPage();
for (const src of website.srcs) {
const to = join(OUT, `${website.name}-${src.name}.png`)
console.log(`Save ${src.href} to ${to}`);
await page.goto(src.href, {waitUntil: 'networkidle2'});
await page.screenshot({ path: to });
}
await page.close()
}))
await browser.close();
})().then(() => {
console.log('Done')
}).catch(err => {
console.error(err)
process.exit(1)
});
export default {}
Conclusion
In this blog post, we have demonstrated how to capture screenshots of web pages using Puppeteer and Node.js. This powerful combination allows developers to automate tasks and perform testing efficiently. By following the provided steps, you can easily incorporate screenshot generation into your projects and create a valuable tool for your web development process.