I’ve recently switched to using PhantomJS for testing and taking screenshots of web pages.
One oddity was having to change the User-Agent
string to render some pages correctly, but this script works fine for most cases:
var page = require('webpage').create(),
system = require('system'),
address, output, size;
if (system.args.length < 3 || system.args.length > 5) {
console.log('Usage: snap.js URL filename');
phantom.exit(1);
} else {
address = system.args[1];
output = system.args[2];
page.viewportSize = page.clipRect = { width: 1280, height: 1024 };
page.customHeaders = {'Referer': address};
page.settings.javascriptEnabled = true;
page.settings.localToRemoteUrlAccessEnabled = true;
page.settings.XSSAuditingEnabled = true;
page.settings.webSecurityEnabled = true;
// this fails on Github
page.settings.userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/536.28.10 (KHTML, like Gecko) Version/6.0.3 Safari/536.28.10';
// this works on Github
page.settings.userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36';
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit();
} else {
window.setTimeout(function () {
page.render(output);
phantom.exit();
}, 7500);
}
});
}