Home >Backend Development >Python Tutorial >How to Run Selenium Tests on Headless Servers without Encountering 'Error: cannot open display: :0'?

How to Run Selenium Tests on Headless Servers without Encountering 'Error: cannot open display: :0'?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-19 02:01:02695browse

How to Run Selenium Tests on Headless Servers without Encountering

Running Selenium in Xvfb: Troubleshooting Display Errors on Headless Servers

Problem:

When running Selenium tests on an Amazon EC2 instance without a graphical user interface (GUI), users may encounter the error:

Error: cannot open display: :0

despite installing necessary packages like Selenium, Firefox, and Xvfb.

Solution:

To run Selenium without a visible display, PyVirtualDisplay or Xvfbwrapper provide headless solutions.

PyVirtualDisplay

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()

Xvfbwrapper

from xvfbwrapper import Xvfb

vdisplay = Xvfb()
vdisplay.start()

# launch stuff inside virtual display here

vdisplay.stop()

Alternatively, for cleaner context management, use Xvfbwrapper as follows:

from xvfbwrapper import Xvfb

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

By using these headless solutions, Selenium tests can run successfully on servers without GUI capabilities, enabling automation and testing in headless environments.

The above is the detailed content of How to Run Selenium Tests on Headless Servers without Encountering 'Error: cannot open display: :0'?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn