在 python 3.6 中尝试使用 Selenium WebDriver 打开网页时出现以下错误?

Getting the following error when trying to open web page with Selenium WebDriver in python 3.6?

当我尝试执行这段代码时:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver= webdriver.Firefox("C:\Program Files\Mozilla Firefox")
driver.get("http://google.com")

我收到以下错误:

C:\Users\vipul\PycharmProjects\newproject\venv\Scripts\python.exe "C:/Users/vipul/PycharmProjects/newproject/Web Scraping.py"
Traceback (most recent call last):
  File "C:\Users\vipul\PycharmProjects\newproject\venv\lib\site-packages\selenium\webdriver\common\service.py", line 74, in start
    stdout=self.log_file, stderr=self.log_file)
  File "C:\Users\vipul\AppData\Local\Programs\Python\Python36-32\Lib\subprocess.py", line 709, in __init__
    restore_signals, start_new_session)
  File "C:\Users\vipul\AppData\Local\Programs\Python\Python36-32\Lib\subprocess.py", line 997, in _execute_child
    startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified

在处理上述异常的过程中,又发生了一个异常:

Traceback (most recent call last):
  File "C:/Users/vipul/PycharmProjects/newproject/Web Scraping.py", line 4, in <module>
    driver= webdriver.Firefox("C:\Program Files\Mozilla Firefox")
  File "C:\Users\vipul\PycharmProjects\newproject\venv\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 148, in __init__
    self.service.start()
  File "C:\Users\vipul\PycharmProjects\newproject\venv\lib\site-packages\selenium\webdriver\common\service.py", line 81, in start
    os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH. 

Process finished with exit code 1

一周前我遇到过同样的问题, 我使用的是 Python 2.7 和 Chrome 的最新版本的网络驱动程序, 然后我传递了 geckodriver 文件路径,如

driver= webdriver.Firefox("c://your-path")

这解决了我的问题,我希望你也能。

将geckodriver.exe下载到特定的folder/directory(例如c:\drivers),然后设置驱动程序路径。

请尝试以下任一方法。

  1. 将驱动程序路径作为参数传递。

    driver= webdriver.Firefox("c:\drivers\geckodriver.exe")
    driver.get("http://google.com")
    
  2. 使用环境设置驱动程序路径。

    import os
    os.environ['webdriver.gecko.driver'] ="c:\drivers\geckodriver.exe"
    driver.get("http://google.com")
    

注意:如果您将 gecko 驱动程序 exe 文件保存在脚本所在的本地文件夹中。则无需设置或传递驱动程序路径。