无法在无头模式下运行Firefox

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (461)

我正在尝试使用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 &

然后我设置Display变量:

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

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

提问于
用户回答回答于

有一个名为PyVirtualDisplay的xvfb包装器似乎是为这个精确的解决方案而设计的。如果您只是执行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()
用户回答回答于

您需要使用无头选项创建驱动程序实例:

from pyvirtualdisplay import Display
from selenium import webdriver


display = Display(visible=0, size=(800, 600))
display.start()

options = webdriver.FirefoxOptions()
options.add_argument("--headless")
driver = webdriver.Firefox(firefox_options=options)

...

希望它能帮到你!

扫码关注云+社区

领取腾讯云代金券