In the following example, we’ll query google for two terms consecutively, “casperjs” 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:

varlinks=[];varcasper=require('casper').create();functiongetLinks(){varlinks=document.querySelectorAll('h3.r a');returnArray.prototype.map.call(links,function(e){returne.getAttribute('href');});}casper.start('http://google.fr/',function(){// Wait for the page to be loadedthis.waitForSelector('form[action="/search"]');});casper.then(function(){// search for 'casperjs' from google formthis.fill('form[action="/search"]',{q:'casperjs'},true);});casper.then(function(){// aggregate results for the 'casperjs' searchlinks=this.evaluate(getLinks);// now search for 'phantomjs' by filling the form againthis.fill('form[action="/search"]',{q:'phantomjs'},true);});casper.then(function(){// aggregate results for the 'phantomjs' searchlinks=links.concat(this.evaluate(getLinks));});casper.run(function(){// echo results in some pretty fashionthis.echo(links.length+' links found:');this.echo(' - '+links.join('\n - ')).exit();});

CoffeeScript is not natively supported in PhantomJS versions 2.0.0 and above. If you are going to use CoffeeScript you’ll have to transpile it into vanilla Javascript. See known issues for more details.