PhantomJS - ilya-khadykin/notes-outdated GitHub Wiki
PhantomJS is a web browser that can be controlled from command line, it is based on WebKit.
Purpose:
- headless website testing
- screen capture
- page automation
- network monitoring
Browser | Engine (2017-01-04) |
---|---|
Safari | WebKit |
Firefox | Gecko |
Google Chrome | Blink |
Internet Explorer | Trident |
Microsoft Edge | EdgeHTML |
Installation
via npm:
npm install -g phantomjs
Error Handling
// your error handler
phantom.onError = function(msg, trace) {
var msgStack = ['PHANTOM ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push( 'TRACE:' );
trace.forEach( function(t) {
msgStack.push( '->' + (t.file || t.sourceURL) + ': ' + t.line
};
console.error( msgStack.join('\n'));
// exit with negative status code
phantom.exit(1);
};
System API
var system = require('system');
var os = system.os;
console.log("You're on " + os.architecture + ' ' + os.name + ' machine.\n');
Read System Arguments
var system = require('system');
var args = system.args;
if (args.length < 2) {
throw new Error( 'Arguments are missing!');
}
var scriptName = args[0];
var name = args[1];
And pass arguments in order:
phantomjs phantom_script.js arg1 arg2 arg3
webpage
API
var system = require('system');
var page = require('webpage').create();
var url = system.args[2];
page.open( url, function( status ) {
console.log('#########################################');
console.log('Opened ' + url + ' with status: ' + status);
page.render('site_screenshot.png');
phantom.exit();
});