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

如何在测试自动化套件目录中自动更新ChromeDriver?

解决ChromeDriver自动更新导致脚本失败的自动化方案

兄弟,我太懂这种每次Chrome更新就要手动换驱动的痛苦了!之前我也踩过这个坑,后来找到了几个完美的自动化解决方案,帮你彻底摆脱手动替换的麻烦:

方案一:使用Selenium 4.6+自带的自动驱动管理(最省心)

如果你用的是Selenium 4.6.0及以上版本,直接躺平就行——Selenium官方已经内置了驱动管理功能,完全不用额外配置:

from selenium import webdriver

# 就这么简单!自动匹配Chrome版本并下载/使用对应驱动
driver = webdriver.Chrome()

它会自动检测本地Chrome的版本,下载匹配的ChromeDriver到系统缓存目录,下次运行直接复用缓存的驱动,全程零手动操作。

方案二:用webdriver-manager第三方库(兼容旧版Selenium)

如果你的Selenium版本低于4.6.0,那webdriver-manager绝对是救星。它专门用来自动管理各种浏览器驱动,操作也很简单:

  1. 先安装库:
pip install webdriver-manager
  1. 修改你的驱动初始化代码:
    原来的代码可能是这样的:
from selenium import webdriver

driver = webdriver.Chrome(executable_path='./drivers/chromedriver')

改成:

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service

# 自动下载匹配版本的ChromeDriver并启动浏览器
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

每次运行脚本时,它会自动检查Chrome版本,下载对应驱动,还会缓存驱动避免重复下载,省心到爆。

方案三:手动实现版本检测与驱动下载(适合自定义需求)

如果你不想依赖任何第三方库,也可以自己写代码实现逻辑,步骤大概是:

  • 获取本地Chrome的主版本号(比如从命令行或注册表读取)
  • 根据版本号拼接对应ChromeDriver的下载链接
  • 下载并解压驱动到指定目录

举个Windows平台的简单示例:

import os
import requests
import zipfile
import subprocess

def get_chrome_main_version():
    # 从注册表获取Chrome版本,提取主版本号
    try:
        result = subprocess.run(
            ['reg', 'query', r'HKEY_CURRENT_USER\Software\Google\Chrome\BLBeacon', '/v', 'version'],
            capture_output=True, text=True, check=True
        )
        full_version = [line for line in result.stdout.split('\n') if 'version' in line.lower()][0].split()[-1]
        return full_version.split('.')[0]
    except Exception as e:
        print(f"获取Chrome版本失败: {e}")
        return None

def download_and_replace_chromedriver(version, save_dir='./drivers'):
    if not version:
        return
    # 构造对应平台的下载链接(这里以Windows为例)
    download_url = f"https://chromedriver.storage.googleapis.com/{version}.0.0.0/chromedriver_win32.zip"
    os.makedirs(save_dir, exist_ok=True)
    zip_path = os.path.join(save_dir, 'chromedriver.zip')

    # 下载驱动包
    try:
        response = requests.get(download_url)
        response.raise_for_status()
        with open(zip_path, 'wb') as f:
            f.write(response.content)
        
        # 解压并替换旧驱动
        with zipfile.ZipFile(zip_path, 'r') as zip_ref:
            zip_ref.extractall(save_dir)
        
        # 清理压缩包
        os.remove(zip_path)
        print(f"成功更新ChromeDriver到版本 {version}")
    except Exception as e:
        print(f"下载驱动失败: {e}")

# 使用示例
chrome_version = get_chrome_main_version()
download_and_replace_chromedriver(chrome_version)

这个方案需要处理不同操作系统的差异(比如macOS/Linux的版本获取命令不同),适合有自定义需求的场景,但不如前两个方案省心。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:13:18