Selenium Tips: Taking ScreenShots on the Server

Code is fantastic at checking for pre-determined problems - that a calculated output matches an expected result. It’s also rather bad at checking for unanticipated changes. One way to do this is to take a screen capture, store it, and compare it to the current screen - a pixel-by-pixel compare. Or store the screencaptures away and have a human review them, perhaps as thumbnails, perhaps overnight. Some of our partner companies, like Applitools, provide extensions to capture certain elements of the screen, but you can get started with plain old vanilla webdriver, using the save_screenshot command. Here’s a working example in ruby and python:

Python: (The full code)

driver = webdriver.Chrome();  
directory = os.path.dirname(os.path.realpath(__file__));
specific_filename = "file://" + directory + "/sample.html";
driver.get(specific_filename);
driver.save_screenshot("screenshot_python.png");
waitforit = raw_input("Press ENTER to continue ...");
driver.quit()

Ruby: (The full code)

driver = Selenium::WebDriver.for :chrome
directory = File.expand_path File.dirname(__FILE__)
specific_filename = "file://" + directory + "/sample.html"
driver.navigate.to specific_filename

#Sleep is for educational purposes only
puts("Press ENTER to continue ...");
waitforit = gets();
driver.save_screenshot("screenshot_orig.png");
puts driver.title
driver.quit

Feel free to take this code out for a spin, it is checked in to GitHub as a running, working example. Fork it and push some contributions back.

Next time we’ll talk about setting the windowsize to make sure the screen captures look identical.

Written by

Matthew Heusser

Topics

Selenium

Categories