You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确初始化Selenium与ChromeDriver,避免参数及路径错误?

解决Selenium TypeError: WebDriver.init() got an unexpected keyword argument 'executable_path' 错误

问题场景

运行以下Python代码验证Selenium与ChromeDriver协同工作:

from selenium import webdriver
# Create an instance of ChromeOptions
options = webdriver.ChromeOptions()

# Specify the path to the chromedriver.exe
chrome_driver_path = 'C:\Users\a2\OneDrive\Desktop\Chromedriver\chromedriver.exe'

# Create a new instance of the Chrome driver using the specified path and options
driver = webdriver.Chrome(executable_path=chrome_driver_path, chrome_options=options)

执行后报错:

Traceback (most recent call last):
 File "D:/f3.py", line 10, in <module>
    driver = webdriver.Chrome(executable_path=chrome_driver_path, options=options)
TypeError: WebDriver.__init__() got an unexpected keyword argument 'executable_path'

注:Chrome与ChromeDriver已安装在同一目录下。

解决方案

这个错误是因为Selenium 4.x版本移除了executable_path参数,同时chrome_options也被统一替换为options,调整代码即可解决:

方法1:通过Service类指定ChromeDriver路径

导入Service类来管理驱动路径,同时修正参数名:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service

options = webdriver.ChromeOptions()
# 路径前加r避免转义字符解析错误
chrome_driver_path = r'C:\Users\a2\OneDrive\Desktop\Chromedriver\chromedriver.exe'

service = Service(chrome_driver_path)
driver = webdriver.Chrome(service=service, options=options)

方法2:自动匹配驱动(推荐)

既然Chrome和ChromeDriver在同一目录,且Chrome通常已加入系统环境变量,Selenium会自动查找匹配的驱动,代码可简化为:

from selenium import webdriver

options = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=options)

内容的提问来源于stack exchange,提问作者Alena Zuruith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 03:52:47