JavaScript Function doc.Support LQDN banner

CasperJS is an open source navigation scripting & testing utility based on PhantomJS, the scriptable headless WebKit engine. It eases the process of defining a full navigation scenario and provides useful high-level functions, methods & syntactic sugar for doing common tasks such as:

  • Defining & ordering navigation steps
  • Filling & submitting forms
  • Clicking links
  • Capturing screenshots of a page (or an area)
  • Making assertions on remote DOM
  • Logging events
  • Downloading base64 encoded resources, even binary ones
  • Writing functional test suites, saving results as JUnit XML

In the following example, we’ll query google for two terms consecutively, “capserjs” and “phantomjs”, aggregate the result links in a standard Array and output the result to the console.

Fire up your favorite editor and save the javascript code below in a googlelinks.js file:

In the following example, we’ll query google for two terms consecutively, “capserjs” and “phantomjs”, aggregate the result links in a standard Array and output the result to the console.

Fire up your favorite editor and save the javascript code below in a googlelinks.js file :

 

var links = [];
var casper = new phantom.Casper();
 
function getLinks() {
    var links = document.querySelectorAll('h3.r a');
    return Array.prototype.map.call(links, function(e) {
        return e.getAttribute('href')
    });
}
 
casper.start('http://google.fr/', function(self) {
    // search for 'casperjs' from google form
    self.fill('form[name=f]', { q: 'casperjs' }, true);
});
 
casper.then(function(self) {
    // aggregate results for the 'casperjs' search
    links = self.evaluate(getLinks);
    // now search for 'phantomjs' by fillin the form again
    self.fill('form[name=f]', { q: 'phantomjs' }, true);
});
 
casper.then(function(self) {
    // aggregate results for the 'phantomjs' search
    links = links.concat(self.evaluate(getLinks));
});
 
casper.run(function(self) {
    // echo results in some pretty fashion
    self.echo(links.length + ' links found:');
    self.echo(' - ' + links.join('\n - ')).exit();
});
 

Leave a Reply