Saturday, April 9, 2016

Basic browsing in casperjs

Suppose we want to browse a site and retrieve the page title using casperjs.

First step is to require and create a new casper instance:

var casper = require('casper').create(
{   verbose: true,
    logLevel: 'debug'                              //logLevel parameter can also be 'error', 'info','warning'
    pageSettings: {
                           userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/53"

                       }
} );


The create() method will then create and return an instance of the casper class.
 Above further optional settings to the create method has been added for debugging, as well
 as a specified useragent.

Second step is to start casper and browse the target site. This is done using the
created casper instance and with it calling the start method:

casper.start(url, function() {// add code here as needed});

The "function()" above denotes a function that may be carried out once the page has been loaded

So let's assume we want to visit google.com:

casper.start(http://google.com);

To browse the google site and print its title:


casper.start(http://www.google.com, function() {
this.echo(this.getTitle(), 'INFO');
});


Messages can be printed in the following range of styles:
'INFO', 'ERROR', 'WARNING', 'COMMENT'

At the end call the run() method with the created casper object:

casper.run();


The resulting code will then be:


 var casper = require('casper').create(
{   verbose: true,
    logLevel: 'debug',
    pageSettings: {
                           userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/53"

                       }

                                      
} );


casper.start(http://www.google.com, function() {
this.echo(this.getTitle, 'INFO');
});

casper.run();



The above code is saved in a .js file and can be executed by running
casperjs filename.js