Codementor Events

How to Capture Website Screenshots in Node

Published Jul 18, 2020
How to Capture Website Screenshots in Node

In this article I'm going to show you how you can capture a website screenshot using Node and screenshotapi.net

First I must set up a new Node project, to do this I run the following commands:

npm init
npm install screenshotapi.net

As you can see, I'm going to rely on the screenshotapi.net package.

Next, I create an index.js file:

const screenshotApiClient = require('screenshotapi.net')('YOUR_API_TOKEN');

screenshotApiClient.saveScreenshotToImage(`screenshot.png`, {
    url: 'https://codementor.io',
    width: 1920,
    height: 1080,
})
.catch((error) => {
    console.error("Error while getting screenshot.");
    console.dir(error);
})

This should save a screenshot of codementor to the screenshot file.
To run the program I run the following command:

node index.js

When I open the screenshot.png file I indeed see a screenshot of codementor!

screenshot.png

Capturing a specific element

Suppose I want to capture a screenshot of the header image. Luckily this is also possible!

The first thing I have to do is get the CSS selector of that image, you can easily find this in Chrome:

#__next > div.jsx-101835301.landing-page > div > div.jsx-2963953577.features > div.jsx-2963953577.features__hero-wrap > div

Then, I have to add this selector to the screenshotapi client:

screenshotApiClient.saveScreenshotToImage(`screenshot.png`, {
    url: 'https://codementor.io',
    width: 1920,
    height: 1080,
    selector: "#__next > div.jsx-101835301.landing-page > div > div.jsx-2963953577.features > div.jsx-2963953577.features__hero-wrap > div"
})
.catch((error) => {
    console.error("Error while getting screenshot.");
    console.dir(error);
})

And when I run this program it shows only the header image!

screenshot.png

Conclusion

That's it! I've shown you how you can play around with screenshots using screenshotapi.net and Node.

Happy coding!

Discover and read more posts from Dirk Hoekstra
get started