为 Windows 安装 Chromedriver - selenium.common.exceptions.WebDriverException:消息:'chromedriver.exe' 可执行文件需要在 PATH 中

Installing Chromedriver for Windows - selenium.common.exceptions.WebDriverException: Message: 'chromedriver.exe' executable needs to be in PATH

我正在尝试使用 Python 和 selenium 进行网络抓取,但我 运行 遇到了这样的错误:

Traceback (most recent call last):
  File "C:/Users/You/your_code.py", line 5, in <module>
    driver = webdriver.Chrome(executable_path='c:\path\to\windows\webdriver\executable.exe')
  File "C:\Users\You\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__
    self.service.start()
  File "C:\Users\You\lib\site-packages\selenium\webdriver\common\service.py", line 81, in start
    raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: 'executable.exe' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home

看来我没有正确安装 selenium 的 chromedriver。如何为 selenium 正确安装 chromedriver?

您可以通过以下几种方式解决此问题:

使用巧克力

我发现安装 chrome 驱动程序的最简单方法是使用 chocolatey. You can follow the instructions to install it here,安装后,只需 运行 choco install chromedriver(作为管理员) ,它应该为您的 chrome.

版本安装 chrome 驱动程序

然后在您的代码中,删除对chrome驱动程序路径的引用:

之前:

driver = webdriver.Chrome(executable_path='c:\path\to\windows\webdriver\executable.exe')

之后:

driver = webdriver.Chrome()

手动

如果您不想使用巧克力味,请按照以下步骤操作

  1. 转到 Chrome 中的 chrome://version/,检查您的当前版本。如您所见,我的版本 89

  1. 转到 chromedriver.chromium.org/downloads 并下载与您的浏览器版本相同的 chrome 驱动程序版本:

  1. 下载适合您 OS 的版本。例如,如果您使用 Windows,请下载 win_32 一个:

  1. 解压缩 .ZIP 并将 chromedriver.exe 放在与 Python 程序相同的文件夹中:

  1. 将 chrome 驱动程序的路径更改为 chromedriver.exe:

之前:

driver = webdriver.Chrome(executable_path='c:\path\to\windows\webdriver\executable.exe')

之后:

driver = webdriver.Chrome(executable_path='chromedriver.exe')

...你应该可以开始了。


正在将 chrome 驱动程序添加到 PATH

如果你想将 chromedriver 添加到 PATH,这样你就不必担心每次编写 selenium 程序时 chromedriver 在哪里,那么它将是只使用巧克力是个好主意,因为它应该在全球范围内安装它。它也更容易,所以如果可以的话就去吧。但是,您仍然可以按照以下步骤手动将 chrome 驱动程序设置为 PATH(对于 Windows):

  1. 打开命令提示符。通过 运行ning
  2. C:\bin 创建一个目录
cd /

...然后:

mkdir bin

...然后:

cd bin

...然后:

explorer .

这应该会在文件资源管理器中打开文件夹:

  1. 将chromedriver.exe放入此文件夹
  2. 通过 运行ning 将其设置为 PATH,在命令提示符中:
setx PATH "%PATH%;C:\bin"

你应该得到这样的东西:

  1. 关闭并重新打开命令提示符
  2. 通过 运行ning chromedriver -v 验证设置。你应该得到这样的东西:
C:\Users\You>chromedriver -v
ChromeDriver 87.0.4280.88 (89e2380a3e36c3464b5dd1302349b1382549290d-refs/branch-heads/4280@{#1761})

如果是这样,你就大功告成了。

添加到 PATH 的说明改编自 here. For other operating systems, see here