You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium ChromeDriver报错求助:升级后无法获取Chrome版本

问题分析与修复方案

核心问题拆解

升级Selenium后,原有代码逻辑完全适配失效,触发多类错误:

  • 系统找不到Chrome注册表键值,无法自动获取浏览器版本
  • Unicode解码异常
  • NameError: name 'webdriver' is not defined
  • 驱动自动下载时的网络连接失败
  • 回退版本未解决问题,说明是代码API适配、环境依赖双重问题

具体修复步骤

1. 修正驱动初始化检查逻辑

原有代码中的webdriver.driver是错误写法,Selenium 4+不存在该属性。正确的驱动实例检查方式如下:

# 全局定义驱动变量
driver = None

# 提前导入核心模块,避免NameError
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service

try:
    # 检查驱动是否已初始化且可用
    if driver is None or not driver.session_id:
        raise Exception("Driver not initialized or invalid")
except:
    # Selenium 4+标准初始化流程
    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service)
    # 后续初始化代码...

2. 解决Chrome版本获取失败(注册表/解码错误)

  • 手动指定Chrome路径:绕过注册表读取,直接设置Chrome二进制文件路径:
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    # Windows示例,替换为你的Chrome实际安装路径
    options.binary_location = r"C:\Program Files\Google\Chrome\Application\chrome.exe"
    driver = webdriver.Chrome(service=service, options=options)
    
  • 修复Unicode解码:启动Python时强制指定UTF-8编码:
    set PYTHONUTF8=1
    python your_script.py
    

3. 解决NameError问题

所有核心模块必须在代码开头导入,禁止仅在try-except块内导入(异常未触发时后续代码会找不到模块):

# 代码顶部必须导入
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service

4. 解决网络连接问题

  • 代理环境适配:如果在代理网络下,给ChromeDriverManager设置代理:
    from webdriver_manager.core.proxy import Proxy
    from webdriver_manager.core.driver_cache import DriverCacheManager
    
    proxy = Proxy(http="http://your-proxy:port", https="http://your-proxy:port")
    cache_manager = DriverCacheManager(proxy=proxy)
    service = Service(ChromeDriverManager(cache_manager=cache_manager).install())
    
  • 手动下载驱动:自动下载失败时,手动下载与Chrome版本匹配的ChromeDriver,直接指定路径:
    service = Service(r"C:\local-path\chromedriver.exe")
    driver = webdriver.Chrome(service=service)
    

5. 彻底重置Selenium环境

  • 完全卸载现有依赖:
    pip uninstall -y selenium webdriver-manager
    
  • 清理pip缓存:
    pip cache purge
    
  • 重新安装稳定版本组合:
    pip install selenium==4.10.0 webdriver-manager==4.0.0
    

内容的提问来源于stack exchange,提问作者jarhead

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 13:41:03