Selenium Chrome驱动初始化报错:options参数重复赋值TypeError
解决Selenium中TypeError: WebDriver.init() got multiple values for argument 'options'错误
错误原因
在Selenium 4.x及以上版本中,webdriver.Chrome的构造函数参数规则发生了变化:第一个位置参数不再是驱动文件路径(executable_path),而是options。你直接传入'chromedriver'作为第一个参数,会被解析为options参数的值,同时又显式指定options=chrome_options,导致重复传递options参数,触发该TypeError。
解决方案
根据你的Selenium版本选择对应写法:
情况1:使用Selenium 4.x及以上版本(推荐)
通过Service类指定ChromeDriver路径:
from selenium import webdriver from selenium.webdriver.chrome.service import Service chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--window-size=2050,2050") chrome_options.add_argument('--headless') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--disable-dev-shm-usage') # 初始化Service对象,传入驱动路径 service = Service('chromedriver') # 传入service和options参数初始化driver driver = webdriver.Chrome(service=service, options=chrome_options)
情况2:使用Selenium 3.x版本
显式指定executable_path参数名,避免参数混淆:
from selenium import webdriver chrome_options = webdriver.ChromeOptions() chrome_options.add_argument("--window-size=2050,2050") chrome_options.add_argument('--headless') chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--disable-dev-shm-usage') # 显式声明executable_path参数 driver = webdriver.Chrome(executable_path='chromedriver', options=chrome_options)
额外提示
如果你的系统环境变量中已经配置了ChromeDriver的路径,无需手动指定驱动文件,直接初始化即可:
driver = webdriver.Chrome(options=chrome_options)
内容的提问来源于stack exchange,提问作者Bers
相关产品推荐
相关产品推荐

