A Drinking Tour of CasperJS – for screen scraping, testing, and profit



A Drinking Tour of CasperJS – for screen scraping, testing, and profit

0 0


drinking-tour-of-casperjs

A quick introduction to CasperJS, what it does, and what it's good for.

On Github founddrama / drinking-tour-of-casperjs

A Drinking Tour of CasperJS

for screen scraping, testing, and profit

or something like that

Rob Friesel / @founddrama

NOT that new Centrify thing that Help Desk is installing for everyone

like a DSL for PhantomJS

(plus a convenient built-in testing toolkit)

installation

$ brew install casperjs
          

or

$ npm install --global casperjs
          

working with web pages

CasperJS

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

casper.start('https://untappd.com/user/founddrama', function() {
  this.echo('The title: "' + this.getHTML('title') + '"');
});

casper.run();
          

$ casperjs simple-casper.js

straight-up PhantomJS

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

webpage.open('https://untappd.com/user/founddrama', function(status) {
  if (status === 'fail') {
    console.error('Failed to open requested page.');
    phantom.exit(1);
  }

  var title = webpage.evaluate(function(selector) {
    return document.querySelector(selector).innerHTML;
  }, 'title');

  console.log('Title is: "' + title + '"');
  phantom.exit();
});
          

$ phantomjs simple-phantom.js

(back to our original problem...)

$ casperjs untappd.js

testing

var credentials = require('./credentials'),
    UNTAPPD     = 'https://untappd.com';

casper.test.begin('Untappd.com demo test thing', function(test) {
  casper
    .start(UNTAPPD + '/login', function() {
      test.assertExists('#username');
      test.assertExists('#password');

      this.fillSelectors('form', {
        '#username': credentials.username,
        '#password': credentials.password
      }, true);
    })
    .thenOpen(UNTAPPD + '/user/' + credentials.username + '/beers', function() {
      test.assertUrlMatch(new RegExp(credentials.username + '/beers$', 'i'),
          'Current URL ends with ' + credentials.username + '/beers');
      test.assertSelectorDoesntHaveText('.info h1', 'Friesel');
      test.assertSelectorHasText('.info .username', credentials.username);
      test.assertTextExists('La Fin Du Monde',
          '"La Fin Du Monde" is on the recent beer history');
    })
    .run(function() {
      test.done();
    });
});
          

$ casperjs test untappd-test.js

Thanks!