Make a browser screenshot in ruby with selenium
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.
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.
Then we load Selenium, indicating the URL we wish to visit and the browser with which we want to visit it.
We load the page, take the screenshot and save the created image.
And we don’t forget to free the memory.
And then the magic happens. Our beautiful screenshot (of the entire page, not only the screen) is then generated.
So who’s ready to start an open source project to generate websites thumbnails using Selenium ? :p