Selenium/PhantomJS 引发错误

Selenium/PhantomJS raises error

我正在尝试 运行 PhantomJS 驱动程序 Python 但我遇到了错误。我读过我应该将整个路径作为参数传递,但它没有帮助。

代码如下:

from selenium import webdriver

# driver = webdriver.Chrome('D:\Python_projects\chromedriver_win32/chromedriver.exe') # this works
driver = webdriver.PhantomJS(executable_path='D:\Python\phantomjs-2.0.0-windows\bin\phantomjs.exe')

错误:

Traceback (most recent call last):
  File "path to script", line 8, in <module>
    driver = webdriver.PhantomJS(executable_path='D:\Python\phantomjs-2.0.0-windows\bin\phantomjs.exe')
  File "C:\Python27\lib\site-packages\selenium\webdriver\phantomjs\webdriver.py", line 50, in __init__
    self.service.start()
  File "C:\Python27\lib\site-packages\selenium\webdriver\phantomjs\service.py", line 75, in start
    raise WebDriverException("Unable to start phantomjs with ghostdriver.", e)
selenium.common.exceptions.WebDriverException: Message: Unable to start phantomjs with ghostdriver.
Screenshot: available via screen

你知道我做错了什么吗?

为简单起见,将可执行文件放在与脚本相同的目录中:

driver = webdriver.PhantomJS() # now there's no need for a path

在原始字符串中创建路径,添加 'r':

driver = webdriver.PhantomJS(executable_path=r'D:\Python\phantomjs-2.0.0-windows\bin\phantomjs.exe')

对我来说 none 以上解决了问题;我找到了代码:

driver = webdriver.PhantomJS()

仅适用于 root...

对我来说,这很好用,也不必为 PhantomJS 指定路径 需要使用pip

安装pip install phantomjs-binary二进制包
pip install phantomjs-binary

它将下载一个大约 60MB 的包。 并根据 运行 环境包含 windows、mac 和 Linux 的 PhantomJS。 之后就可以使用了

from selenium import webdriver
from phantomjs_bin import executable_path

driver = webdriver.PhantomJS(executable_path=executable_path)