首次运行Selenium+Python测试失败,求助配置问题排查
问题解决:Selenium运行报错AttributeError: 'str' object has no attribute 'capabilities'
错误原因
你使用的是Selenium 4.x及以上版本,该版本不再支持直接向webdriver.Chrome()传入驱动路径字符串。原写法是Selenium 3的兼容用法,4.x会将传入的字符串识别为options参数(要求是ChromeOptions对象),因此触发类型错误。
两种解决方法
方法一:通过Service类指定驱动路径
如果需要手动指定本地的chromedriver路径,需导入Service类封装路径后传入:
from selenium import webdriver from selenium.webdriver.chrome.service import Service # 用Service类封装驱动文件路径 service = Service('./chromedriver') driver = webdriver.Chrome(service=service) driver.get("https://www.python.org") print(driver.title) driver.quit() # 执行完记得关闭浏览器实例
方法二:使用Selenium Manager自动管理驱动(推荐)
Selenium 4.6.0及以上版本自带Selenium Manager工具,会自动检测Chrome版本并下载匹配的chromedriver,无需手动下载和指定路径,代码可简化为:
from selenium import webdriver driver = webdriver.Chrome() # 无需传入路径,自动处理驱动 driver.get("https://www.python.org") print(driver.title) driver.quit()
内容的提问来源于stack exchange,提问作者Agustin Leonangeli
相关产品推荐
相关产品推荐

