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
Release: 2024-11-19 02:01:02
Original
695 people have browsed it

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
Copy after login

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()
Copy after login

Xvfbwrapper

from xvfbwrapper import Xvfb

vdisplay = Xvfb()
vdisplay.start()

# launch stuff inside virtual display here

vdisplay.stop()
Copy after login

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.
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template