Selenium自动下载浏览器驱动
为什么需要自动下载浏览器驱动?
血泪场景重现
-
新人入职第一天:
- 花3小时配置Chrome/Firefox驱动
- 版本不匹配导致
SessionNotCreatedException
-
浏览器自动更新后:
- 所有测试脚本突然崩溃
- 手动查找驱动耗时长
终极解决方案:自动下载驱动
✅ 动态检测浏览器版本
✅ 下载匹配的驱动程序
✅ 自动设置环境变量
3行代码极简解决方案(Python版)
安装必备库
pip install webdriver-manager # 核心神器
自动下载驱动示例
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)
执行效果
[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:强制更新最新驱动
# 忽略缓存强制下载
ChromeDriverManager(version="latest").install()
场景2:指定特定版本
# 下载指定版本驱动(兼容旧浏览器)
ChromeDriverManager(version="114.0.5735.90").install()
场景3:设置代理和镜像源
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:自定义缓存路径
# 修改默认存储位置
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)
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");}
}
常见故障排除指南
-
下载速度慢
- 解决方案:使用国内镜像源
ChromeDriverManager(url="https://registry.npmmirror.com/-/binary/chromedriver").install()
- 解决方案:使用国内镜像源
-
公司网络禁止访问
- 解决方案:先手动下载驱动,再指定路径
driver = webdriver.Chrome(executable_path="D:/drivers/chromedriver.exe")
- 解决方案:先手动下载驱动,再指定路径
-
证书验证错误
- 解决方案:关闭SSL验证(仅限测试环境)
ChromeDriverManager(ssl_verify=False).install()
- 解决方案:关闭SSL验证(仅限测试环境)
-
权限不足
- Linux/Mac解决方案:
sudo chmod +x /path/to/chromedriver
- Linux/Mac解决方案:
完整代码
默认是Chrome,会自动下载安装对应的版本Driver
# Selenium 4.33.0from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from common.tools import get_project_path, sepclass 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 WebDriverdriver = webdriver.Chrome(service=service, options=chrome_options)# 删除所有cookiesdriver.delete_all_cookies()return driver
如果是Firefox,需要修改参数:
#!/usr/bin/python3
# coding=utf-8
# @Time: 2025/6/5 18:18
# @Author: Samfrom selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.firefox.options import Options
from common.tools import get_project_path, sepclass 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 WebDriverdriver = webdriver.Firefox(service=service, options=firefox_options)# 删除所有cookiesdriver.delete_all_cookies()return driver
「小贴士」:点击头像→【关注】按钮,获取更多软件测试的晋升认知不迷路! 🚀