运行 vps 上的硒

running Selenium on a vps

我有一个简单的 python 脚本,可以在我的本地机器上正常运行。但是如果我尝试在我的 vps 上 运行 它,我会得到一个错误:

Traceback (most recent call last):
  File "test.py", line 15, in <module>
    browser = webdriver.Firefox(profile)
  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 constructor, check it for details.

这是脚本:

from selenium import webdriver

profile = webdriver.FirefoxProfile()

profile.set_preference('permissions.default.image', 2)
# Set all new windows to open in the current window instead
profile.set_preference('browser.link.open_newwindow', 1)
browser = webdriver.Firefox(profile)
browser.get('http://www.google.com/')
html = browser.page_source

print html

browser.close()

由于 vps 没有 GUI,是什么导致了错误?

您必须正确使用 xvfb 包到 运行 webdriver。

usr/bin/xvfb-run /usr/bin/python myfile.py

检查 This link 了解更多详情