Some time ago, a PHP wanabee (berk), Romain 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 installed.
sudo 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 portfolio.
We start with the magic and explain after.
require 'rubygems'
require 'selenium'
# We load Selenium
@selenium = Selenium::SeleniumDriver.new("localhost", 4444, "*firefox", "http://42.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.
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.
@selenium = Selenium::SeleniumDriver.new("localhost", 4444, "*firefox", "http://42.dmathieu.com/", 10000);
@selenium.start
We load the page, take the screenshot and save the created image.
@selenium.open "/"
@selenium.capture_entire_page_screenshot(File.expand_path(File.dirname(__FILE__)) + 'screenshot.png', '');
And we don't forget to free the memory.
@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


Comments