直接结论:用 webdriver-manager,别再手动下载或硬编码路径。它能自动读取本地 chrome/edge/firefox 版本,下载匹配驱动,缓存复用,且兼容 selenium 4.11+(包括你正在用的 4.18.0);其核心是调用系统命令或读取注册表/info.plist 获取浏览器主版本号,再从 chrome for testing 官方源精准拉取对应驱动,全过程无需浏览器运行、不依赖预装驱动。

直接结论:用 webdriver-manager,别再手动下载或硬编码路径。 它能自动读取本地 Chrome/Edge/Firefox 版本,下载匹配驱动,缓存复用,且兼容 Selenium 4.11+(包括你正在用的 4.18.0)。
为什么 ChromeDriverManager().install() 能自动匹配版本?
它不是猜,而是实打实查——先调用系统命令(如 chrome --version 或读取注册表/macOS Bundle Info),提取主版本号(如 126.0.6478.127 → 主版本是 126),再从 Chrome for Testing 官方源拉取对应驱动。整个过程不依赖浏览器是否运行,也不需要你提前装好任意一个 chromedriver。
- Windows 下会尝试读取注册表
HKEY_CURRENT_USER\Software\Google\Chrome\BLBeacon或chrome.exe文件属性 - macOS 通过
/Applications/Google Chrome.app/Contents/Info.plist提取 CFBundleShortVersionString - Linux 直接执行
google-chrome --version或chromium-browser --version - 失败时会 fallback 到
requests请求https://googlechromelabs.github.io/chrome-for-testing/获取最新映射表
替换旧代码时最容易踩的坑
很多人照着老教程改,结果报 TypeError: 'Service' object is not callable 或 WebDriverException: unknown error: cannot find Chrome binary。核心问题就两个:
- 还在用已弃用的
executable_path参数:Selenium 4.11+ 必须用Service对象传入,不能直接传字符串路径 - 漏配
options.binary_location:如果你把 Chrome 装在非默认路径(比如便携版、企业定制版),webdriver-manager不会帮你找浏览器,只管驱动 - CI/CD 环境没装 Chrome:
webdriver-manager只下载驱动,不装浏览器。Docker 镜像里得提前apt-get install chromium-browser或类似操作
正确写法示例:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options from webdriver_manager.chrome import ChromeDriverManager <p>options = Options() options.binary_location = "/opt/google/chrome/chrome" # 非默认路径必须显式指定 service = Service(ChromeDriverManager().install()) # ✅ 不是字符串,是 Service 实例 driver = webdriver.Chrome(service=service, options=options)</p>
Edge 和 Firefox 怎么做?
API 完全一致,只是换包名和类名:
- Edge:
from webdriver_manager.microsoft import EdgeChromiumDriverManager,搭配webdriver.Edge(service=Service(...)) - Firefox:
from webdriver_manager.firefox import GeckoDriverManager,搭配webdriver.Firefox(service=Service(...)) - 注意:Edge 的
binary_location默认是msedge(Linux/macOS)或msedge.exe(Windows),若自定义安装路径,同样要手动设
所有驱动都走同一套缓存逻辑,默认存在 ~/.cache/selenium,第二次运行基本不下载。
真正麻烦的从来不是“怎么装”,而是“谁来保证环境里有浏览器”。webdriver-manager 解决了驱动侧的不确定性,但浏览器本身还得你来管——尤其是无头服务器、Docker 或 CI runner 上,别等脚本报 no such file or directory: chrome 才想起来装 Chrome。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











