July 4, 2011

Python - Taking Browser Screenshots With No Display (Selenium/Xvfb)

In my last two blog posts, I showed examples of using Selenium WebDriver to capture screenshots, and running in a headless (no X-server) mode.

This example combines the two solutions to capture screenshots inside a virtual display.

To achieve this, I use a combination of Selenium WebDriver and pyvirtualdisplay (which uses xvfb) to run a browser in a virtual display and capture screenshots.

the setup you need is:

  • Selenium 2 Python bindings: PyPI
  • pyvirtualdisplay Python package (depends on xvfb): PyPI

On Debian/Ubuntu Linux systems, you can install everything with:

$ sudo apt-get install python-pip xvfb xserver-xephyr
$ sudo pip install selenium

once you have it setup, the following code example should work:

#!/usr/bin/env python

from pyvirtualdisplay import Display
from selenium import webdriver

display = Display(visible=0, size=(800, 600))
display.start()

browser = webdriver.Firefox()
browser.get('http://www.google.com')
browser.save_screenshot('screenie.png')
browser.quit()

display.stop()

this will:

  • launch a virtual display
  • launch Firefox browser inside the virtual display
  • navigate to google.com
  • capture and save a screenshot
  • close the browser
  • stop the virtual display

5 comments:

Panggi Libersa Jasri Akadol said...

How to make it just capture at the failure point ? and do you have any idea to capture video of the tests ? :)

Pixy Misa said...

This is far and away the simplest solution for automated browser screenshots I've seen.

Quite why it's so complex I have no idea.

Anonymous said...

Have you looked at PhantomJS? It can do this and much more :)

Anonymous said...

@Panggi - add the screen capture code to an exception handler for the test case to execute when asserts fail.

@ahaxopet - The problem there is that it's not using an actual browser, so you can't fully test compatibility with Firefox, Chrome, IE, etc... just against their JS library.

Yonatan said...

This is a simple solution that provides accurate results with even the latest HTML5/SVG features.

I've been struggling with wkhtmltopdf and phantomjs compatibility issues for a long time.

Thanks!