如何解决ChromeDriver初始化时的AttributeError错误?
Selenium AttributeError: 'str' object has no attribute 'capabilities' 解决方案
问题代码
from selenium import webdriver from selenium.webdriver.common.by import By import time driver = webdriver.Chrome(r'C:\dchrome\chromedriver.exe') driver.get('https://www.smv.gob.pe/SIMV/') time.sleep(3) driver.quit()
报错信息
Traceback (most recent call last): File "c:\Users\Sebas\OneDrive\Escritorio\Visual Studio Code\Python\index.py", line 7, in <module> driver = webdriver.Chrome(r'C:\dchrome\chromedriver.exe') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Sebas\OneDrive\Escritorio\Visual Studio Code\Python\RT_IL\Lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 45, in __init__ super().__init__( File "C:\Users\Sebas\OneDrive\Escritorio\Visual Studio Code\Python\RT_IL\Lib\site-packages\selenium\webdriver\chromium\webdriver.py", line 50, in __init__ if finder.get_browser_path(): ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Sebas\OneDrive\Escritorio\Visual Studio Code\Python\RT_IL\Lib\site-packages\selenium\webdriver\common\driver_finder.py", line 47, in get_browser_path return self._binary_paths()["browser_path"] ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Sebas\OneDrive\Escritorio\Visual Studio Code\Python\RT_IL\Lib\site-packages\selenium\webdriver\common\driver_finder.py", line 56, in _binary_paths browser = self._options.capabilities["browserName"] ^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'str' object has no attribute 'capabilities'
错误原因
你使用的是Selenium 4.x版本,但代码写法沿用了Selenium 3的格式。在Selenium 4中,webdriver.Chrome()的第一个参数不再接受驱动路径字符串,而是需要传入ChromeOptions对象;驱动路径必须通过Service类来指定。直接传入路径字符串会被程序识别为options参数,导致后续调用capabilities属性时触发类型错误。
修复方案
方案1:手动指定ChromeDriver路径
通过Service类传入驱动路径:
from selenium import webdriver from selenium.webdriver.chrome.service import Service import time # 指定ChromeDriver路径 service = Service(r'C:\dchrome\chromedriver.exe') driver = webdriver.Chrome(service=service) driver.get('https://www.smv.gob.pe/SIMV/') time.sleep(3) driver.quit()
方案2:自动管理ChromeDriver(推荐)
使用webdriver-manager库自动匹配并下载对应版本的ChromeDriver,无需手动指定路径:
- 先安装依赖:
pip install webdriver-manager
- 改写代码:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager import time # 自动获取对应版本的ChromeDriver driver = webdriver.Chrome(service=Service(ChromeDriverManager().install())) driver.get('https://www.smv.gob.pe/SIMV/') time.sleep(3) driver.quit()
额外注意事项
- 确保Chrome浏览器版本与ChromeDriver版本完全匹配(主版本号一致即可,比如Chrome 125对应ChromeDriver 125.x)。
- 避免硬编码路径,优先使用环境变量或自动管理工具,提升代码可移植性。
- 若仍有问题,检查虚拟环境是否正确激活,Selenium库是否为最新稳定版。
内容的提问来源于stack exchange,提问作者Sebastian Gómez Tenorio
相关产品推荐
相关产品推荐

