Home >Backend Development >Python Tutorial >How to Run Selenium Headless in Xvfb on an EC2 Instance?

How to Run Selenium Headless in Xvfb on an EC2 Instance?

Barbara Streisand
Barbara StreisandOriginal
2024-12-01 09:02:14889browse

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!

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