Posted on Leave a comment

How do I Run Selenium in Xvfb

Many people utilize the Selenium WebDriver for interaction automation with a browser, either Chrome, Selenium, Firefox, etc. However, the need to have another computer that possesses a desktop environment to execute this automation can be quite tasking and stressful. Usually, when different scenarios need to be executed, a browser will be launched by Selenium, and the script will be executed.

Installing the Xvfb

It is possible to utilize the headless Command-line argument in Chrome and Firefox. You are, however, required to configure your webdrivers to suit this command, but you need to know that while the majority of them will support this, some won’t. This has proven to be a good option for support on different platforms. The Xvfb is a display server that majorly functions to implement the X11 display server protocol. You can run any application in headless mode through this program. As opposed to the usual operation of outputting the Graphics User interface on your screen, it instead produces a virtual framebuffer which displays the User interface there. To install the Xvfb, you need to run the following code:

sudo apt-get install xvfb

To use this program easily, you can execute any command that requires a screen through the Xvfb-run Command.

xvfb-run ./Runner

In a case as above, the Runner is a console application that utilizes the Selenium to execute the automation process in browsers like Chrome and Firefox. Through this, you can successfully make the GUI application headless.

It is also possible to utilize the PyVirtualDisplay, which is a python wrapper for Xvfb, to execute any headless WebDriver tests.

#!/usr/bin/env python
from pyvirtualdisplay import Display
from selenium import webdriver
display = Display(visible=0, size=(800, 600))
display.start()
# now Firefox will run in a virtual display.
# you will not see the browser.
browser = webdriver.Firefox()
browser.get('http://www.google.com')
print browser.title
browser.quit()
display.stop()

It is also possible to utilize the Xvfbwrapper, which possess an identical module without any external dependencies.

from xvfbwrapper import Xvfb
vdisplay = Xvfb()
vdisplay.start()
# launch stuff inside virtual display here
vdisplay.stop()

or in another way, you can use it as a context manager

from xvfbwrapper import Xvfb
with Xvfb() as xvfb:
    # launch stuff inside virtual display here.
    # It starts/stops in this code block