Selenium firefox webdriver 在一台机器上工作,但不能在另一台机器上工作

Selenium's firefox webdriver works in one machine but not another

这是我运行宁的非常简单的代码:

from selenium import webdriver
driver = webdriver.Firefox()`

这是它在 google 计算实例上导致的错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py", line 77, in __init__
    self.binary, timeout),
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/extension_connection.py", line 49, in __init__
    self.binary.launch_browser(self.profile)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/firefox_binary.py", line 68, in launch_browser
    self._wait_until_connectable()
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/firefox_binary.py", line 98, in _wait_until_connectable
    raise WebDriverException("The browser appears to have exited "
selenium.common.exceptions.WebDriverException: Message: The browser appears to have exited before we could connect. If you specified a log_file in the FirefoxBinary construct
or, check it for details.

我在两台机器上都有

一台机器 运行 在 google 计算服务器上(出错),另一台机器在 VM VirtualBox 上(它工作),但这是我能找到的唯一区别应该没关系。

还有哪些其他差异可能会在一台机器上导致此错误,而在另一台机器上不会?

注意: 我在想也许 google 计算引擎无法打开浏览器 window 因为你只能通过 ssh 进入命令行?那么这个问题就不能解决了吗?

注意: 此代码适用于两台机器:

from selenium import webdriver
driver = webdriver.PhantomJS

但是,我需要使用 firefox,所以这不是一个解决方案,只是需要记住的另一件事。

我需要 运行 'gcloud init' 然后默认登录。请参阅第 1 步的文档:https://cloud.google.com/compute/docs/gcloud-compute/

如您所述,原因可能是您 运行 在无头系统上。 PhantomJS 和 HTMLUnit 以及诸如此类的东西不需要 x 服务器。

您可以尝试在命令行中键入 firefox 来启动 firefox 吗? 如果失败并出现 Can't find/open display on 0.0 或 smth 之类的异常。像这样,你应该使用 XVFB:

这里是关于如何使用 XVFB 的说明。

sudo apt-get update
sudo apt-get install firefox xvfb
sudo Xvfb :10 -ac
export DISPLAY=:10

现在您可以尝试使用 firefox

启动 firefox

我复制的命令: http://www.installationpage.com/selenium/how-to-run-selenium-headless-firefox-in-ubuntu/

如果您想在 java 应用程序中设置 DISPLAY 端口,并且仅针对您的 firefox 实例,您可以这样做:

    FirefoxBinary firefoxBinary = new FirefoxBinary();
    firefoxBinary.setEnvironmentProperty("DISPLAY", ":10");

    new FirefoxDriver(firefoxBinary, new FirefoxProfile());