PhantomJS AN INTRO

http://phantomjs.org/


By Taswar Bhatti

taswar@gmail.com

@taswarbhatti

WHO AM I?

I work as a Web Geek, MS .NET during the day and Linux, dynamic languages during the night :)

Author of Instant AutoMapper on Packt Publishing

WhatZ PhantomJS

PhantomJS is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handing, CSS selector, JSON, Canvas and SVG


WhatZ it GOOD FOR?

  • Headless WebSite Testing
  • Screen Capture
  • Page Automation
  • Network Monitoring

INStall Version

http://phantomjs.org/download.html
Latest: 1.9.2
Windows EXE version
Mac OSX version (Homebrew or Binary)
Linux version

Simple Screen Capture

var page = require('webpage').create();
page.open('http://github.com/', function () {
    page.render('github.png');
    phantom.exit();
});

Beside PNG format, PhantomJS supports JPEG, GIF, and PDF

INcludING JQUERY

Eliminate the need to use document.getElementById

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

page
.open('http://www.whatever.com', function() {

var jq = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js";
 
page.includeJs(jq, function() {
  page.evaluate(function() { $("button").click(); //using jquery to find element }); phantom.exit() }); });

Can USE coffeeScript

system = require 'system'
if system.args.length is 1
console.log 'Try to pass some args when invoking this script!'
else
for arg, i in system.args
console.log i + ': ' + arg
phantom.exit()

Scraping DATA

var page = require('webpage').create(),
url = 'http://www.dzone.com/links/index.html';

page.open(url, function (status) {
if (status !== 'success') {
console.log('Unable to access ' + url);
} else {
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js", function() {
var result = page.evaluate(function() {
var stories = $("a[rel='bookmark']"), a, a_txt,
news = [], i = stories.length;

for(; i >= 0; i -= 1){
a = $(stories[i]);

a_txt = a.text() || '';
if(a_txt !== '') {
news.push(a.text().trim() + " | " + a.attr('href'));
}
}

return news;
});
console.log(result.join('\n'));

phantom.exit();
});
}
});

Integrating with Languages

DEMO

Demo Ruby on Rails Screenshot

Demo Python/Ruby WebDriver Sample

More samples located at https://github.com/ariya/phantomjs

THANK YOU

Twitter: @taswarbhatti

Blog: http://taswar.zeytinsoft.com

Contact: taswar@gmail.com

Code: https://github.com/taswar/ottawajs-dec2013

PhantomJS

By Taswar Bhatti

PhantomJS

  • 1,576
Loading comments...