dmathieu - Make a browser screenshot in ruby with selenium

Make a browser screenshot in ruby with selenium

Wednesday, 9 December 2009 in Development Articles by Damien Mathieu Creative Commons License

Some time ago, I was looking to make a web page screenshot only with command line. Many solutions have been proposed. But my prefered one is Selenium. So I’ve decided to look closer into that.

First you need to have Selenium RC installed and launched. It’s pretty simple. Download it, go to the selenium-server-1.0 and enter in command line

java -jar selenium-server.jar

Your Selenium server is started on the 4444 port, ready to be used ! You also need the selenium-client gem installed.

gem install selenium-client

Your hard drive is now a bit less empty. We can start having fun with code ! :) I want to do a screenshot of my blog.

We start with the magic and explain after.

1
2
3
4
5
6
7
8
9
10
11
12
13
require 'rubygems'
require 'selenium'

# We load Selenium
@selenium = Selenium::SeleniumDriver.new('localhost', 4444, '*firefox', 'http://dmathieu.com', 10000);
@selenium.start

# We go to the main page and take the screenshot
@selenium.open '/';
@selenium.capture_entire_page_screenshot(File.expand_path(File.dirname(__FILE__)) + 'screenshot.png', '');

# We unload Selenium
@selenium.stop

We load the required libraries. Not complicated. We only need Selenium.

1
2
require 'rubygems'
require 'selenium'

Then we load Selenium, indicating the URL we wish to visit and the browser with which we want to visit it.

1
2
@selenium = Selenium::SeleniumDriver.new('localhost', 4444, '*firefox', 'http://dmathieu.com/', 10000);
@selenium.start

We load the page, take the screenshot and save the created image.

1
2
@selenium.open '/';
@selenium.capture_entire_page_screenshot(File.expand_path(File.dirname(__FILE__)) + 'screenshot.png', '');

And we don’t forget to free the memory.

1
@selenium.stop

And then the magic happens. Our beautiful screenshot (of the entire page, not only the screen) is then generated.

You’ll notice that javascript is executed (try to deactivate it on your browser, you won’t see my email on the page anymore). And the render is what we have in the browser.

So who’s ready to start an open source project to generate websites thumbnails using Selenium ? :p