Sunday, July 18, 2010

Make a browser screenshot in Ruby with Selenium


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 !
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.

http://dmathieu.com/en/ruby/make-a-browser-screenshot-in-ruby-with-selenium

No comments: