Selenium初始化Chrome报TypeError: options参数多值传参问题排查
错误原因及解决方案
错误根源
你遇到的TypeError: __init__() got multiple values for argument 'options'是因为Selenium 4.x版本调整了Chrome驱动初始化的参数规则:
- 在Selenium 3中,
Chrome类的第一个位置参数是executable_path(驱动路径); - 升级到Selenium 4后,
executable_path不再作为位置参数,改为关键字参数,同时Chrome类的第一个位置参数变为options。
你的代码直接将驱动路径作为位置参数传入(比如Chrome(ChromeDriverManager().install(), options=chrome_options)),Python会把这个位置参数解析成options参数,随后你又通过options=chrome_options关键字传入了另一个值,导致参数重复,触发错误。
修复方案
有两种可行的修复方式:
方式1:用关键字参数指定驱动路径
将驱动路径通过executable_path=关键字传入,修改代码如下:
try: driver = Chrome(executable_path=ChromeDriverManager().install(), options=chrome_options) except Exception as e: print(e) try: driver = Chrome(executable_path="./chromedriver", options=chrome_options) except Exception: driver = Chrome(executable_path="chromedriver.exe", options=chrome_options)
方式2:使用Selenium 4推荐的Service类(更规范)
Selenium 4官方推荐用Service类管理驱动,调整代码如下:
from selenium.webdriver.chrome.service import Service # 新增导入 # ... 其他代码保持不变 ... try: driver = Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options) except Exception as e: print(e) try: driver = Chrome(service=Service("./chromedriver"), options=chrome_options) except Exception: driver = Chrome(service=Service("chromedriver.exe"), options=chrome_options)
内容的提问来源于stack exchange,提问作者quarks
相关产品推荐
相关产品推荐

