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:
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
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)





