如何正确初始化Selenium与ChromeDriver,避免参数及路径错误?
解决Selenium TypeError: WebDriver.init() got an unexpected keyword argument 'executable_path' 错误
问题场景
运行以下Python代码验证Selenium与ChromeDriver协同工作:
from selenium import webdriver # Create an instance of ChromeOptions options = webdriver.ChromeOptions() # Specify the path to the chromedriver.exe chrome_driver_path = 'C:\Users\a2\OneDrive\Desktop\Chromedriver\chromedriver.exe' # Create a new instance of the Chrome driver using the specified path and options driver = webdriver.Chrome(executable_path=chrome_driver_path, chrome_options=options)
执行后报错:
Traceback (most recent call last): File "D:/f3.py", line 10, in <module> driver = webdriver.Chrome(executable_path=chrome_driver_path, options=options) TypeError: WebDriver.__init__() got an unexpected keyword argument 'executable_path'
注:Chrome与ChromeDriver已安装在同一目录下。
解决方案
这个错误是因为Selenium 4.x版本移除了executable_path参数,同时chrome_options也被统一替换为options,调整代码即可解决:
方法1:通过Service类指定ChromeDriver路径
导入Service类来管理驱动路径,同时修正参数名:
from selenium import webdriver from selenium.webdriver.chrome.service import Service options = webdriver.ChromeOptions() # 路径前加r避免转义字符解析错误 chrome_driver_path = r'C:\Users\a2\OneDrive\Desktop\Chromedriver\chromedriver.exe' service = Service(chrome_driver_path) driver = webdriver.Chrome(service=service, options=options)
方法2:自动匹配驱动(推荐)
既然Chrome和ChromeDriver在同一目录,且Chrome通常已加入系统环境变量,Selenium会自动查找匹配的驱动,代码可简化为:
from selenium import webdriver options = webdriver.ChromeOptions() driver = webdriver.Chrome(options=options)
内容的提问来源于stack exchange,提问作者Alena Zuruith
相关产品推荐
相关产品推荐

