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
Release: 2024-12-01 09:02:14
Original
898 people have browsed it

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

Xvfbwrapper Approach:

from xvfbwrapper import Xvfb

vdisplay = Xvfb()
vdisplay.start()

# launch stuff inside virtual display here

vdisplay.stop()
Copy after login

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

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!

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