使用selenium模块的webdriver遇到了问题:FileNotFoundError: [WinError 2] 系统找不到指定的文件。

问题遇到的现象和发生背景

跟着书本学习selenium模块,安装了最新的 Firefox
敲入下列代码后报错:

问题相关代码,请勿粘贴截图

from selenium import webdriver
browser = webdriver.Firefox()
运行结果及报错内容
Traceback (most recent call last):
  File "C:\Users\SCGF\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\common\service.py", line 71, in start
    self.process = subprocess.Popen(cmd, env=self.env,
  File "C:\Users\SCGF\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 966, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\SCGF\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 1435, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] 系统找不到指定的文件。

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\SCGF\AppData\Roaming\Sublime Text\Packages\User\songsPythonFiles\selenium_test.py", line 2, in <module>
    browser = webdriver.Firefox()
  File "C:\Users\SCGF\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 174, in __init__
    self.service.start()
  File "C:\Users\SCGF\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\common\service.py", line 81, in start
    raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH. 


我的解答思路和尝试过的方法

完全看不懂在说什么。不知道是否与firefox有关系?

我想要达到的结果
  1. 求帮忙解决问题
  2. 追加问题:为啥书里非要用firefox做这些例子?

你看看你的浏览器的版本和你下载的selenium的驱动版本是不是一样的,我怀疑你没有安装selenium的驱动

使用selenium是需要下载一个selenium的驱动Webdriver的
chrome驱动下载地址
http://chromedriver.storage.googleapis.com/index.html
firefox 驱动下载地址
https://github.com/mozilla/geckodriver/releases/
使用火狐的原因---个人喜好吧,我用chrome,哈哈哈哈。

附加一份浏览器初始化的一下设置

    def __init__(self):
        self.path = os.path.dirname(os.path.abspath(__file__)) + ".\chromedriver.exe"
        chrome_options = Options()
        chrome_options.add_argument('--headless' )
        chrome_options.add_argument('--no-sandbox')
        # chrome_options.add_argument("--disable-javascript")
        chrome_options.add_argument("--user-data-dir=C:\chrome_HONG")
        chrome_options.add_argument(
            'user-agent=Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36')
        self.driver = Chrome(self.path, options=chrome_options)

selenium是通过浏览器驱动去模拟浏览器操作的,你是下了火狐,但还需要去官网下一个与火狐浏览器版本一样的浏览器驱动,browser = webdriver.Firefox()默认调用的geckodriver(也就是你刚下载的浏览器驱动)是默认与你当前写代码的py文件一个路径,你下载完可以放在当前目录下,再试试。