Selenium自动下载浏览器驱动

为什么需要自动下载浏览器驱动?

血泪场景重现

  1. 新人入职第一天

    • 花3小时配置Chrome/Firefox驱动
    • 版本不匹配导致SessionNotCreatedException
  2. 浏览器自动更新后

    • 所有测试脚本突然崩溃
    • 手动查找驱动耗时长

终极解决方案:自动下载驱动

✅ 动态检测浏览器版本

✅ 下载匹配的驱动程序

✅ 自动设置环境变量


3行代码极简解决方案(Python版)

安装必备库
bash 复制代码
pip install webdriver-manager  # 核心神器
自动下载驱动示例
python 复制代码
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager

# Chrome自动下载(会返回驱动路径)
driver_path = ChromeDriverManager().install()  

# 创建浏览器实例(无需手动指定路径)
driver = webdriver.Chrome(executable_path=driver_path)
driver.get("https://www.baidu.com")

# Firefox同样简单
firefox_path = GeckoDriverManager().install()
driver = webdriver.Firefox(executable_path=firefox_path)
执行效果
bash 复制代码
[WDM] - Current google-chrome version is 124.0.6367
[WDM] - Get LATEST driver version for 124.0.6367
[WDM] - Driver [C:\Users\Sam\.wdm\drivers\chromedriver\win64\124.0.6367.78\chromedriver.exe] found in cache

核心原理拆解(文字版流程图)

复制代码
1. 检测已安装的浏览器版本
   │
   ├── Windows:查询注册表 `HKEY_CURRENT_USER\Software\Google\Chrome\BLBeacon`
   ├── macOS:执行 `/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --version`
   ├── Linux:解析 `google-chrome --version` 输出
   │
2. 访问官方驱动仓库(无需翻墙镜像)
   │
   ├── Chrome:https://chromedriver.storage.googleapis.com
   ├── Firefox:https://github.com/mozilla/geckodriver/releases
   │
3. 下载匹配版本驱动
   │
   ├── 自动识别操作系统(Win/Mac/Linux)
   ├── 解压压缩包到缓存目录
   │
4. 返回驱动绝对路径

进阶实战:自定义控制方案

场景1:强制更新最新驱动
python 复制代码
# 忽略缓存强制下载
ChromeDriverManager(version="latest").install()
场景2:指定特定版本
python 复制代码
# 下载指定版本驱动(兼容旧浏览器)
ChromeDriverManager(version="114.0.5735.90").install()
场景3:设置代理和镜像源
python 复制代码
import os

# 方法1:设置环境变量
os.environ["WDM_PROXY"] = "http://company-proxy:8080"

# 方法2:代码配置
ChromeDriverManager(
    proxy="http://user:pass@proxy:8080",  # 代理
    url="https://npm.taobao.org/mirrors/chromedriver"  # 国内镜像
).install()
场景4:自定义缓存路径
python 复制代码
# 修改默认存储位置
ChromeDriverManager(cache_valid_range=30,  # 缓存有效期30天
                    path="/tmp/my_drivers" # 自定义目录
                   ).install()

跨语言支持方案

语言 库名称 安装命令
Java webdrivermanager mvn io.github.bonigarcia:webdrivermanager:5.6.3
NodeJS webdriver-manager npm install webdriver-manager
C# WebDriverManager.Net dotnet add package WebDriverManager
Java示例(Spring Boot)
java 复制代码
import io.github.bonigarcia.wdm.WebDriverManager;

public class AutoDriverTest {
    public static void main(String[] args) {
        // 自动下载Chrome驱动
        WebDriverManager.chromedriver().setup();
        
        // 创建浏览器实例
        WebDriver driver = new ChromeDriver();
        driver.get("https://baidu.com");
    }
}

常见故障排除指南

  1. 下载速度慢

    • 解决方案:使用国内镜像源

      python 复制代码
      ChromeDriverManager(url="https://registry.npmmirror.com/-/binary/chromedriver").install()
  2. 公司网络禁止访问

    • 解决方案:先手动下载驱动,再指定路径

      python 复制代码
      driver = webdriver.Chrome(executable_path="D:/drivers/chromedriver.exe")
  3. 证书验证错误

    • 解决方案:关闭SSL验证(仅限测试环境)

      python 复制代码
      ChromeDriverManager(ssl_verify=False).install()
  4. 权限不足

    • Linux/Mac解决方案:

      bash 复制代码
      sudo chmod +x /path/to/chromedriver

完整代码

默认是Chrome,会自动下载安装对应的版本Driver

python 复制代码
# Selenium 4.33.0

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from common.tools import get_project_path, sep


class DriverConfig:
    def driver_config(self):
        """
        浏览器驱动配置
        :return: 配置好的WebDriver实例
        """
        # 创建ChromeOptions并配置
        chrome_options = Options()
        chrome_options.add_argument("window-size=1920,1080")
        # 去除"Chrome正受到自动测试软件的控制"的提示
        chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
        # 解决selenium无法访问https的问题
        chrome_options.add_argument("--ignore-certificate-errors")
        # 允许忽略localhost上的TLS/SSL错误
        chrome_options.add_argument("--allow-insecure-localhost")
        # 设置无痕模式
        # chrome_options.add_argument("--incognito")
        # 设置为无头模式
        # chrome_options.add_argument("--headless")
        # 解决卡顿:GPU加速
        chrome_options.add_argument("--disable-gpu")
        # 解决卡顿:禁用 Chrome 的沙箱安全机制。
        chrome_options.add_argument("--no-sandbox")
        # 解决卡顿:测试用例一多的化,可能会导致内存溢出,要加上这个
        chrome_options.add_argument("--disable-dev-shm-usage")

        # Selenium 4.10+ 版本后无需手动指定driver路径,会自动管理
        # 但如果需要指定自定义路径,可以使用以下方式
        # service = Service(executable_path="/path/to/chromedriver")

        # 使用默认的驱动管理功能
        service = Service()

        # 使用Service和Options初始化Chrome WebDriver
        driver = webdriver.Chrome(service=service, options=chrome_options)

        # 删除所有cookies
        driver.delete_all_cookies()

        return driver

如果是Firefox,需要修改参数:

python 复制代码
#!/usr/bin/python3
# coding=utf-8
# @Time: 2025/6/5 18:18
# @Author: Sam

from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.firefox.options import Options
from common.tools import get_project_path, sep

class DriverConfig:
    def driver_config(self):
        """
        浏览器驱动配置
        :return: 配置好的WebDriver实例
        """
        # 创建FirefoxOptions并配置
        firefox_options = Options()
        firefox_options.add_argument("--width=1920")
        firefox_options.add_argument("--height=1080")
        # 去除"Firefox正受到自动测试软件的控制"的提示
        # Firefox默认不会显示此提示
        # 解决selenium无法访问https的问题
        firefox_options.accept_insecure_certs = True
        # 设置为无头模式
        # firefox_options.add_argument("--headless")
        # 解决卡顿:禁用GPU加速
        firefox_options.add_argument("--disable-gpu")
        # 解决卡顿:禁用沙箱安全机制
        firefox_options.add_argument("--no-sandbox")
        # 解决卡顿:禁用共享内存使用
        firefox_options.add_argument("--disable-dev-shm-usage")

        # Selenium 4.10+ 版本后无需手动指定driver路径,会自动管理
        # 使用默认的驱动管理功能
        service = Service()
        
        # 使用Service和Options初始化Firefox WebDriver
        driver = webdriver.Firefox(service=service, options=firefox_options)

        # 删除所有cookies
        driver.delete_all_cookies()

        return driver

「小贴士」 :点击头像→【关注】按钮,获取更多软件测试的晋升认知不迷路! 🚀

相关推荐
测试老哥5 小时前
Jmeter如何进行多服务器远程测试?
自动化测试·软件测试·功能测试·测试工具·jmeter·测试用例·性能测试
程序员杰哥10 小时前
Postman常见问题及解决方法
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·postman
天才测试猿14 小时前
Postman接口测试之postman设置接口关联,实现参数化
自动化测试·软件测试·python·测试工具·职场和发展·接口测试·postman
程序员杰哥2 天前
接口自动化测试之pytest 运行方式及前置后置封装
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
互联网杂货铺2 天前
功能测试、性能测试、安全测试详解
自动化测试·软件测试·python·功能测试·测试工具·性能测试·安全性测试
测试老哥2 天前
Pytest+Selenium UI自动化测试实战实例
自动化测试·软件测试·python·selenium·测试工具·ui·pytest
天才测试猿3 天前
接口自动化测试之pytest接口关联框架封装
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
互联网杂货铺3 天前
unittest自动化测试实战
自动化测试·软件测试·python·测试工具·程序人生·职场和发展·测试用例