Capture Your Site with PhantomJS

“Hey! What kind of stuff is PhantomJS?”. This could be the first time for you to hear or read or use PhantomJS, but for you guys who don’t, you still can read this article, because I still need your traffic (kidding).

PhantomJS is a headless WebKit scriptable with Javascript API.

So, what does “headless WebKit” mean? It’s like a browser (WebKit based browser), but without the GUI. So, you can use many kinds of WebKit functions in your own scripts. Then, you may ask “what is it used for?”. PhantomJS is used for headless website testing, page automation, network monitoring, and page automation.

The reason I play with this stuff is because I had a simple idea that capturing website automatically. People just give the URI of the page and the application will get the screen shot of it. Then, it can be shared or organized by that person. At first, I thought that I was going to have a tough journey to get thing done, fortunately I wasn’t.

So, we will start from installing the phantomJS. Since I worked in MacOS environment, so I used homebrew and executed this command

$> brew update && brew install phantomjs

If you already have your homebrew installed at the default application path, you can use phantomjs command right away, after the installation. We have the cooking tool, now let’s make our recipe by creating a file named capture.js. Write this code within the file.

var page = require('webpage').create(), 
    system = require('system'), 
    uri; 

if (system.args.length === 1) { 
  console.log('Usage: capture.js <url>'); 
  phantom.exit(); 
} 

uri = system.args[1]; 
page.open(uri, function (status) { 
  if (status !== 'success') { 
    console.log('URL is invalid or not found'); 
  } else { 
    page.render(‘captured.png'); 
  } 
  phantom.exit(); 
});

Let’s start the cooking by executing this command

$> phantomjs capture.js http://hafizbadrie.wordpress.com

You will find that there’s a new file named captured.png that contains the screen shot of my blog homepage. Cool isn’t it?

Now, try finding a lot cooler stuff with phantomJS. Cheers!

About these ads

One thought on “Capture Your Site with PhantomJS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s