2

我正在尝试使用 Xvfb 使用 Firefox 在无头模式下运行 Python + Selenium 脚本,但出现错误。没有太多可用于 Xvfb 解决问题的文档或指南,因此请在此处寻求帮助。

环境信息:
操作系统:CentOS 6.5 版(最小安装)
Xvfb:xorg-x11-server-Xvfb-1.15.0
Firefox:52.8.0
geckodriver:0.24.0
Python:3.6.7

后续步骤:

一旦完成安装上述要求。我开始了一个虚拟显示:

$Xvfb :1 -ac &

另外,我尝试过:

$Xvfb :1 -screen 0 1024x768x24 -extension RANDR &

然后我设置显示变量:

export DISPLAY=:1

当我尝试在 Python 控制台中启动 Selenium WebDriver 时,我收到错误连接被拒绝

> from selenium import webdriver
> from pyvirtualdisplay import Display
> display = Display(visible=0, size=(800, 600))
> display.start()
> driver = webdriver.Firefox()

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.6/site-packages/selenium/webdriver/firefox/webdriver.py", line 174, in __init__
keep_alive=True)
File "/usr/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 157, in __init__
self.start_session(capabilities, browser_profile)
File "/usr/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 252, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "/usr/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/usr/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: connection refused

任何帮助或建议将不胜感激。

4

1 回答 1

0

xvfb 周围有一个名为PyVirtualDisplay的包装器,它似乎是为这个精确的解决方案而设计的。如果您只是执行pip install pyvirtualdisplay以下脚本,则应该运行一个无头 Firefox 窗口:

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(executable_path="/Users/username/Location/geckodriver")
browser.get('http://www.google.com')
print browser.title
browser.quit()

display.stop()
于 2019-03-21T17:04:51.860 回答