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

Jupyter中调用chromedriver触发AttributeError错误的解决求助

解决Selenium调用ChromeDriver时的AttributeError错误

问题场景

编写程序在Chrome浏览器中打开特定页面时,调用chromedriver出现错误,原代码及报错信息如下:

原代码

from selenium import webdriver
driver = webdriver.Chrome('webdriver//chromedriver.exe')

报错信息

--------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[4], line 1
----> 1 driver = webdriver.Chrome('webdriver//chromedriver.exe')

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\selenium\webdriver\chrome\webdriver.py:45, in WebDriver.__init__(self, options, service, keep_alive)
     42 service = service if service else Service()
     43 options = options if options else Options()
---> 45 super().__init__(
     46     browser_name=DesiredCapabilities.CHROME["browserName"],
     47     vendor_prefix="goog",
     48     options=options,
     49     service=service,
     50     keep_alive=keep_alive,
     51 )

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\selenium\webdriver\chromium\webdriver.py:50, in ChromiumDriver.__init__(self, browser_name, vendor_prefix, options, service, keep_alive)
     47 self.service = service
     49 finder = DriverFinder(self.service, options)
---> 50 if finder.get_browser_path():
     51     options.binary_location = finder.get_browser_path()
     52     options.browser_version = None

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\selenium\webdriver\common\driver_finder.py:47, in DriverFinder.get_browser_path(self)
     46 def get_browser_path(self) -> str:
---> 47     return self._binary_paths()["browser_path"]

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\selenium\webdriver\common\driver_finder.py:56, in DriverFinder._binary_paths(self)
     53 if self._paths["driver_path"]:
     54     return self._paths
---> 56 browser = self._options.capabilities["browserName"]
     57 try:
     58     path = self._service.path

AttributeError: 'str' object has no attribute 'capabilities'

解决方案

错误根源是Selenium 4.x及以上版本中,webdriver.Chrome()的第一个参数不再支持直接传入驱动路径字符串,必须通过Service对象来指定驱动路径。

修正后的代码

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

# 用Service对象封装chromedriver路径
service = Service('webdriver//chromedriver.exe')
# 传入service参数启动浏览器
driver = webdriver.Chrome(service=service)

# 示例:打开目标页面
# driver.get("https://your-target-page.com")

简化方案(自动查找驱动)

如果你的Chrome浏览器与chromedriver版本匹配,且驱动已配置到系统环境变量中,或者Selenium能自动识别驱动位置,可以省略手动指定路径:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://your-target-page.com")

内容的提问来源于stack exchange,提问作者Elkin Rivera

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 04:19:51