PhantomJS

From Code Self Study Wiki
Jump to: navigation, search

See http://phantomjs.org/ and some tips.

Sample Scripts[edit]

var webPage = require('webpage');
var page = webPage.create();
 
// Log requests
page.onResourceRequested = function (request) {
    console.log('Request ' + JSON.stringify(request, undefined, 4));
};
 
// Log responses
page.onResourceReceived = function (response) {
    console.log('Response (#' + response.id + ', stage "' + response.stage + '"): ' + JSON.stringify(response));
};
 
// Change user-agent
page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36';
 
// Add other headers
page.customHeaders = {'Referer': 'https://www.google.com/'};
 
// Fetch a page
page.open('https://www.google.com/', function (status) {
    console.log('Status: ' + status);
    if (status === 'success') {
        // Take a screenshot
        page.render('screenshot.png');
    }
    phantom.exit();
});

SSL Errors[edit]

If there are SSL problems or the page is failing for some reason, try telling Phantom to ignore SSL errors: phantomjs --ignore-ssl-errors=true file.js.