
本文详解如何修复 Selenium 4 及以上版本中 WebDriver.__init__() 报错“unexpected keyword argument 'executable_path'”,通过 Service 类正确配置 ChromeDriver 路径,并兼容新版 Chrome 浏览器。
本文详解如何修复 selenium 4 及以上版本中 `webdriver.__init__()` 报错“unexpected keyword argument 'executable_path'”,通过 `service` 类正确配置 chromedriver 路径,并兼容新版 chrome 浏览器。
自 Selenium 4.0 起,官方正式弃用了 executable_path 参数,将其移入独立的 Service 类进行管理。这是为了统一 WebDriver 的驱动生命周期控制(如启动、停止、日志配置等),提升跨浏览器驱动管理的一致性与可维护性。因此,旧写法:
driver = webdriver.Chrome(options=options, executable_path=r'chromedriver.exe')
会触发 TypeError: WebDriver.__init__() got an unexpected keyword argument 'executable_path'。
✅ 正确写法(Selenium 4.0+ 推荐):
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
def main():
options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_experimental_option('detach', True)
# ✅ 使用 Service 显式指定 chromedriver 路径
service = Service(r'chromedriver.exe') # 支持绝对路径或相对路径
driver = webdriver.Chrome(service=service, options=options)
driver.get('https://discord.com/login')
# 后续逻辑保持不变...
? 关键变更说明:
- Service 类替代了 executable_path 参数;
- service 参数必须显式传入 webdriver.Chrome() 构造函数;
- 若 chromedriver.exe 不在当前目录,请使用绝对路径(如 r'C:\path\to\chromedriver.exe')或确保其位于系统 PATH 中(此时可传空 Service())。
⚠️ 注意事项:
- 版本匹配:务必确保 chromedriver.exe 版本与本地 Chrome 浏览器主版本号一致(例如 Chrome 126 → 需用 ChromeDriver 126.x)。可通过 chrome://version 查看浏览器版本,并从 ChromeDriver 官方下载页 获取对应驱动。
- 权限与路径:Windows 下建议使用原始字符串(r'')避免转义问题;Linux/macOS 用户需赋予执行权限:chmod +x chromedriver。
- 自动管理(进阶推荐):可配合 webdriver-manager 库实现驱动自动下载与缓存(无需手动下载):
pip install webdriver-manager
from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager service = Service(ChromeDriverManager().install()) driver = webdriver.Chrome(service=service, options=options)
该方式彻底规避版本兼容与路径配置问题,适合生产环境及 CI/CD 流程。
最后提醒:本文示例代码涉及 Discord 登录流程与 Token 提取,仅限教育与安全研究用途。未经明确授权,自动化获取他人账户凭证违反《计算机信息系统安全保护条例》及 Discord 服务条款,请严格遵守法律法规与平台政策。











