无法以无头模式运行Firefox

时间:2019-03-21 16:36:21

标签: python-3.x selenium xvfb centos6.5 firefox-headless

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

环境信息:
操作系统:CentOS 6.5版(最小安装)
Xvfb:xorg-x11-server-Xvfb-1.15.0
Firefox:52.8.0
壁虎驱动程序: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

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

1 个答案:

答案 0 :(得分: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()