Xvfb:运行 测试脚本时连接被拒绝

Xvfb: connection refused when running test script

我有一个 python 脚本,它只能通过调用 my.ip.address/test 来触发。如果我通过命令行 运行 PHP 代码,它工作正常。

但是,如果我使用指定的 url 通过浏览器访问测试自动化,它会给我这个错误:

Traceback (most recent call last): File "scripts/crawler.py",
line 10, in driver = webdriver.Firefox(capabilities={"marionette":True}) File "/usr/lib/python2.7/site-packages/selenium/webdriver/firefox/webdriver.py",
line 152, in __init__ keep_alive=True) File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py",
line 98, in __init__ self.start_session(desired_capabilities, browser_profile) File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py",
line 188, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py",
line 252, in execute self.error_handler.check_response(response) File "/usr/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py",    
line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: connection refused

geckodriver.log 错误:

1495299180874   geckodriver::marionette INFO    Starting browser /usr/lib/firefox/firefox with args ["-marionette"]
Unable to init server: Could not connect: Connection refused
Error: cannot open display: :99

已经安装了Xvfb和运行它:

$ whoami
  codekaizer #with root privileges
$ Xvfb :99 -screen 0 1024x768x24 -ac -fbdir /tmp/.X11-unix/X99 &

运行 PHP /test 端点的代码片段:

$cmd = 'xvfb-run -a python scripts/crawler.py'
return shell_exec($cmd);

Python代码参考:

#!/usr/bin/env python2

from pyvirtualdisplay import Display
from selenium import webdriver   
import time
import sys

driver = webdriver.Firefox(capabilities={"marionette":True})

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

driver.get('https://www.google.com')
print driver.title
driver.close()
display.stop()

我现在很困惑,非常感谢有人的帮助!

详情:

谢谢! -ck

您正在混合使用 Xvfb 的两种不同方法:运行从命令行使用它,运行从 pyvirtualdisplay 使用它。命令行方法不起作用的原因是因为您没有将新的 Xvfb 实例连接到系统显示,而 pyvirtualdisplay 方法不起作用的原因是因为您试图在 pyvirtualdisplay 创建浏览器之前实例化浏览器将浏览器实例的虚拟帧缓冲区添加到 运行 中。选择一种方法,但不要同时使用两种方法。

如果您想从命令行运行它,您还必须导出您的 DISPLAY 以匹配您设置的端口:

Xvfb :99 -screen 0 1024x768x24 -ac -fbdir /tmp/.X11-unix/X99 &
export DISPLAY=:99

python yourscript.py

或者,更好的方法是让 pyvirtualdisplay 以编程方式管理所有这些,就像您几乎正在做的那样:

#!/usr/bin/env python2

from pyvirtualdisplay import Display
from selenium import webdriver   
import time
import sys

# Use an context manager to handle the start() and stop()
# Instantiate Display BEFORE you try to instantiate the driver
with Display(visible=0, size=(800,600)):
    driver = webdriver.Firefox(capabilities={"marionette":True})

    try:
        driver.get('https://www.google.com')
        print driver.title
    finally:
        # A try/finally block like this insures the driver is closed even if an exception is thrown
        driver.close()