Taking a screenshot with webdriver (python)

An essential part of debugging for web based tests is the ability to grab a screenshot of the current page. A good test design should automatically take screenshots of important pages for manual review or any time an assertion fails.

Fortunately, Selenium Webdriver makes this very easy. Below is an example of taking screenshots using Webdriver and python. Taking a screenshot with python is as simple as calling driver.get_screenshot_as_file('screenshot.png'). However, it is useful to provide a wrapper function to perform any additional tasks such as creating required directories. Note: Most webdriver browser implementations (webdriver.Firefox(), webdriver.Chrome(), etc) provide a driver.save_screenshot() method as a wrapper around get_screenshot_as_file().

The code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import os
 
## Save a screenshot of the current page.
#  @param driver A webdriver object.
#  @param name The name of the file to save.
#  @param save_location Where to save the screenshot.
#  @return The full path to the saved image.
def take_screenshot(driver, name, save_location):
  # Make sure the path exists.
  path = os.path.abspath(save_location)
  if not os.path.exists(path):
    os.makedirs(path)
  full_path = %s/%s' % (path, name)
  driver.get_screenshot_as_file(full_path)
  return full_path

Example usage

1
2
3
4
5
6
7
from selenium import webdriver
 
driver = webdriver.Firefox()
driver.get('http://www.google.com')
screenshot = take_screenshot(driver, 'google.png', 'path/to/screenshots')
print "Screenshot saved to: %s" % screenshot
driver.quit()
Tweet

Comments:

Subscribe & Contact

Know how to listen, and you will profit even from those who talk badly.
~ Plutarch ~