Have you ever wonder how you can take screenshot of webpages programmatically? I certainly did. I wanted to periodically monitor changes on a webpage and didn’t want to do it by hand everyday. Being the lazy programmer that I am, I wanted to automate this, and so I did some digging and found a very cool nodejs based tool and I would like to share it with you today.
node-webshot
node-webshot is an amazing module built on top of PhantomJs that allows you to quickly and painlessly take screenshots of any webpage from any screen size.
Let’s install the module first:
npm install webshot
create index.js and type in the following:
const webshot = require('webshot');
webshot('http://www.penta-code.com', 'pentacode.png', function(err) {
if (!err) {
console.log('Screenshot taken!');
}
});
run it and you should see a file call pentacode.png appear on the same directory as your index.js file (you can also place the file anywhere by directly specifying the path of output file, for example ‘./output/pentacode.jpg’) Easy right?
Selector Based Screenshot
You can also take screenshots of specific regions too! Simply provide it an option parameter with the name of the selector (jquery based selector convention) to the captureSelector parameter :
// Selector screenshot
const optionsSelector = {
captureSelector: '.tr-container'
};
webshot('http://www.penta-code.com', 'pentacode-selector.png', optionsSelector, function(err) {
if (!err) {
console.log('Screenshot taken!');
}
});
Mobile Screenshot
What if you want screenshots of the mobile website? Webshot can handle that no problem:
// Mobile screenshot
const optionsMobile = {
screenSize: {
width: 414,
height: 736
},
shotSize: {
width: 414,
height: 'all'
},
userAgent: 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.20 (KHTML, like Gecko) Mobile/7B298g'
};
webshot('http://www.penta-code.com', 'pentacode-mobile.png', optionsMobile, function(err) {
if (!err) {
console.log('Screenshot taken!');
}
});
Just pass in an option and define your screen size, user agent and shot size and webshot will take care of it!
Handy isn’t it? The power behind this module is PhantomJS, a Webkit based headless browser. There are a lot more you can do with this module and I suggest you head over to the project github to try out some of other options you may pass to it to fully leverage its capabilities. Hope you enjoy this tutorial.
If you enjoyed this tutorial, make sure to subscribe to our Youtube Channel and follow us on Twitter @pentacodevids for latest updates!