Home >Backend Development >Python Tutorial >How to Run Selenium Headless in Xvfb on an EC2 Instance?
Running Selenium in Xvfb
Problem Description:
When attempting to run Selenium in Xvfb on an EC2 instance, users encounter an error: "cannot open display: :0".
Solution:
To run Selenium in Xvfb headless mode, utilize PyVirtualDisplay or xvfbwrapper for Python.
PyVirtualDisplay Approach:
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') print browser.title browser.quit() display.stop()
Xvfbwrapper Approach:
from xvfbwrapper import Xvfb vdisplay = Xvfb() vdisplay.start() # launch stuff inside virtual display here vdisplay.stop()
Using xvfbwrapper with a Context Manager:
from xvfbwrapper import Xvfb with Xvfb() as xvfb: # launch stuff inside virtual display here # It starts/stops in this code block.
The above is the detailed content of How to Run Selenium Headless in Xvfb on an EC2 Instance?. For more information, please follow other related articles on the PHP Chinese website!