一尘不染

Python-如何在Xvfb中运行Selenium?

python

我在EC2实例上。因此没有GUI。

$pip install selenium
$sudo apt-get install firefox xvfb

然后我这样做:

$Xvfb :1 -screen 0 1024x768x24 2>&1 >/dev/null &

$DISPLAY=:1 java -jar selenium-server-standalone-2.0b3.jar
05:08:31.227 INFO - Java: Sun Microsystems Inc. 19.0-b09
05:08:31.229 INFO - OS: Linux 2.6.32-305-ec2 i386
05:08:31.233 INFO - v2.0 [b3], with Core v2.0 [b3]
05:08:32.121 INFO - RemoteWebDriver instances should connect to: http://127.0.0.1:4444/wd/hub
05:08:32.122 INFO - Version Jetty/5.1.x
05:08:32.123 INFO - Started HttpContext[/selenium-server/driver,/selenium-server/driver]
05:08:32.124 INFO - Started HttpContext[/selenium-server,/selenium-server]
05:08:32.124 INFO - Started HttpContext[/,/]
05:08:32.291 INFO - Started org.openqa.jetty.jetty.servlet.ServletHandler@1186fab
05:08:32.292 INFO - Started HttpContext[/wd,/wd]
05:08:32.295 INFO - Started SocketListener on 0.0.0.0:4444
05:08:32.295 INFO - Started org.openqa.jetty.jetty.Server@1ffb8dc

太好了,现在一切正常,对吗?

当我运行代码时:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox() 
browser.get("http://www.yahoo.com") 

我得到这个:

Error: cannot open display: :0

阅读 865

收藏
2020-02-16

共2个答案

一尘不染

打开终端并运行此命令 xhost +。每次重新启动计算机时都需要运行此命令。如果一切正常,可以将其添加到启动命令中

还要确保在/ etc / environment文件中有一行

export DISPLAY=:0.0 

然后,运行测试以查看问题是否得到解决。

在使用此功能之前,请所有人注意以下来自sardathrion的评论。

2020-02-16
一尘不染

你可以使用PyVirtualDisplayXvfb的Python包装器)运行无头WebDriver测试。

#!/usr/bin/env python

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()

或更妙的是,将其用作上下文管理器:

from xvfbwrapper import Xvfb

with Xvfb() as xvfb:
    # launch stuff inside virtual display here.
    # It starts/stops in this code block.
2020-02-16