无法使用Python安装Selenium WebDriver

Can't install Selenium WebDriver with Python

我正在尝试在Mac上安装Selenium WebDriver和Python。我用了这个命令:

1
sudo easy_install selenium

之后,我尝试了以下简单的测试:

Python

1
2
from selenium import webdriver
driver = webdriver.Firefox()

我得到了以下错误。我做错什么了?

Traceback (most recent call last):
File"", line 1, in
File"/Library/Python/2.7/site-packages/selenium-3.0.0.b3-py2.7.egg/selenium/webdriver/firefox/webdriver.py", line 68, in init
self.service.start() File"/Library/Python/2.7/site-packages/selenium-3.0.0.b3-py2.7.egg/selenium/webdriver/common/service.py", line 71, in start
os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.


如果不带任何参数调用Selenium驱动程序,则WebDriver可执行文件的路径必须位于系统路径环境变量中。

或者,可以显式指定路径,如下所示:

1
driver = webdriver.Firefox("path/to/the/FireFoxExecutable")


错误是告诉您找不到geckodriver。GeckoDriver是一个附加组件,您必须安装它来控制火狐。它不包括在硒包装中,因此必须单独安装。

下面的shell脚本将从Mozilla的repo下载最新的geckoDriver,并将其放在usr/local/bin中,以便在您的路径上找到它:

1
2
3
4
5
6
#!/bin/sh
url=$(curl -s"https://api.github.com/repos/mozilla/geckodriver/releases/latest" | python -c"import sys, json; r = json.load(sys.stdin); print [a for a in r['assets'] if 'linux64' in a['name']][0]['browser_download_url'];")
curl -L -o geckodriver.tar.gz $url
tar -xzf geckodriver.tar.gz
chmod +x geckodriver
sudo mv geckodriver /usr/local/bin

(通过pipeasy_install安装selenium后运行此脚本)