Writing PhantomJS scripts

We know how to write JavaScript, and now we know that there are several PhantomJS JavaScript APIs and objects. We also have learned the basics of the PhantomJS command-line arguments. We are now ready to create our own scripts.

We will create a simple script to load a site and then display the title of the page when loaded successfully. Finally, we will exit. If the page fails to load, we will log some message to the console.

var page = require('webpage').create();
page.open("http://www.packtpub.com", function(status) {
   if ( status === "success" ) {
      console.log(page.title); 
   } else {
      console.log("Page failed to load."); 
   }
   phantom.exit(0);
});

The preceding PhantomJS script is very simple. First, we import the webpage module, ...

Get Getting Started with PhantomJS now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.