Selenium新版本运行异常求助:基础Chrome自动化代码无法执行
Selenium Chrome自动化代码故障排查与修复
核心排查点
- 版本不匹配:Chrome浏览器和ChromeDriver的大版本必须完全一致(比如Chrome 120对应ChromeDriver 120.x.x.x),哪怕小版本差异都可能导致启动失败
- 路径异常:你的代码里路径混合了
\和/,虽然raw字符串能兼容,但Windows环境下统一用\或借助os.path模块拼接更稳妥;OneDrive同步文件夹可能有权限限制,建议把驱动移到本地非同步目录 - 权限问题:右键ChromeDriver.exe,检查是否有执行权限,必要时以管理员身份运行脚本
- Selenium版本:确保安装的是Selenium 4.x及以上版本,旧版本API调用逻辑不同
推荐修复方案(自动管理驱动)
用webdriver-manager自动匹配驱动版本,彻底解决路径和版本兼容问题:
先安装依赖:
pip install webdriver-manager
替换后的代码:
from selenium import webdriver from selenium.webdriver.chrome.options import Options from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.service import Service options = Options() # 按需添加配置,比如无头模式:options.add_argument("--headless=new") service = Service(ChromeDriverManager().install()) driver = webdriver.Chrome(service=service, options=options) driver.get("https://www.google.com")
手动指定路径的修复方案
如果坚持用本地驱动,修正路径格式并确保版本匹配:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options import os options = Options() # 用os.path拼接避免路径格式错误 chrome_driver_path = os.path.join( "C:", "Users", "DHOBLYA", "OneDrive - Hapag-Lloyd AG", "Desktop", "Processes", "adhoc", "chromedriver-win64", "chromedriver.exe" ) service = Service(executable_path=chrome_driver_path) driver = webdriver.Chrome(service=service, options=options) driver.get("https://www.google.com")
内容的提问来源于stack exchange,提问作者Yash Dhoble
相关产品推荐
相关产品推荐

