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!