PhantomJS + CasperJS Part II

Task Automation and Testing

From part I, I did not explain what the code does.

// common js syntax
var casper = require('casper').create(); // Instantiate Casper object
casper.echo("Hello World.", "INFO"); // Casper JS style Hello World
casper.exit(); // 

Sample Project 1

Capture image of web of Google.com and Whatsapp.surge.sh

var casper = require('casper').create();

casper.start('http://www.google.com', function() {
    this.capture('./output/google.png');
});
casper.thenOpen('http://whatsapp.surge.sh', function() {
    this.capture('./output/ws.png');
});


casper.run(function() {
    this.exit();
});

Sample Project 2

Get title tag of Google page

var casper = require('casper').create();

casper.start('http://www.google.com', function() {

    var pageTitle = this.evaluate(function() {
        var title = document.title;
        return title;
    });
    this.echo(pageTitle, "INFO");    
});
casper.run(function() {
    this.exit();
});

Sample Project 3

casper.on()

var casper = require('casper').create();

casper.on('remote.message', function(msg) {
    console.log('remote message is: ' + msg);
});

casper.start('http://www.google.com', function() {
    var pageTitle = this.evaluate(function(msg) {
        var title = document.title;
        console.log(title);
    });
});

casper.run(function() {
    this.exit();
});

However, the evaluate part can be replaced just with casper.getTitle()

check out casper documentation for more util function

Casper Fill method

Search Google with "hello world!"

var casper = require('casper').create();

casper.on('remote.message', function(msg) {
    console.log('remote message is: ' + msg);
});

casper.start('http://www.google.com', function() {
    this.fill('form', {q: "hello world!"}, true);
});
casper.then(function() {
    this.capture('./output/search.png');
});

casper.run(function() {
    this.exit();
});

change then() to wait() to enable wait for the page to wait to load

casper.wait(1000, function() {
    this.capture('./output/search.png');
});

profile image
Written by Lai Weng Han