Thursday, February 7, 2013

Taking screenshots of multiple sites using casperjs

Casperjs, together with Phantomjs, allows you to take screenshots of web pages without the need to launch a graphical browser like FF or Chrome.

The many examples on the net unfortunately skipped the issue of taking screenshots of multiple sites per execution. Also, the ones I've tried kept getting mobile versions of the sites I intended to capture.

So I decided to piece together the disparate info out there and do some tests to come up with a foolproof way to achieve what I wanted.

Before we go to the script, here's a visual guide of the variables used in it. The top, left corner is the (0,0) position. The image we want to take for each site is the clipped region at the center. The viewport width was set to a whooping 2000 to prevent sites like engadget.com from returning their mobile version.

Here is the Casperjs script. All images are dumped in the 'shots' directory relative to the script itself. The comments should hopefully guide you into understanding and subsequently modifying it for your testing needs.

// // Usage : casperjs casper_1.js

// // Size of the browser i.e. viewport
var view_width = 2000, view_height = 768;

// // Size of the clipped image
var clip_width = 1366, clip_height = 768;

var casper = require("casper").create({
 // // Set the viewport size
 viewportSize: {width: view_width, height: view_height},
 // // Set the position and the size of the clipped image
 clipRect: { 
  top: 0, 
  left: (view_width - clip_width)/2, 
  width: clip_width, 
  height: clip_height 
 }
});

// // Take screenshots of these sites
var links = [
    "http://engadget.com/",
    "http://shoryuken.com/2013/02/01/help-save-super-arcade/",
    "http://theverge.com/"
];

casper.start();
var i = 0;

casper.each(links, function(self, link) {
    this.thenOpen(link, function() {
        i++;

        // // Output to console on the current page's title
        this.echo(i + ' : ' + this.getTitle() + " @ " + link);

        // // Dump screenshots to directory 'shots'
        this.capture('shots/casper_1_' + i + '.png');
    });
});

casper.run();