在 Mac 上配置 ChromeDriver 的正确步骤如下:
1. 基础配置流程
(1) 确认浏览器版本
# 打开 Chrome 访问以下地址查看版本
chrome://version/
# 终端查看版本号 (示例输出: 125.0.6422.113)
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --version
(2) 移动驱动到系统路径
# 解压下载的 chromedriver_mac64.zip
unzip ~/Downloads/chromedriver_mac64.zip
# 将驱动移动到可执行目录
sudo mv chromedriver /usr/local/bin
# 赋予执行权限
sudo chmod +x /usr/local/bin/chromedriver
(3) 验证安装
# 终端执行验证
chromedriver --version
# 应输出类似: ChromeDriver 125.0.6422.113 (a8a16a6b4c114c385e1a0f02c75c26d233ba2f0d-refs/branch-heads/6422@{#981})
2. 自动化版本管理方案
使用 WebDriver Manager (推荐)
pip install webdriver-manager
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
# 自动下载匹配的驱动
service = webdriver.ChromeService(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
driver.get("https://www.google.com")
print(driver.title)
driver.quit()
3. 常见问题解决
(1) 权限问题
# 如果出现 Permission denied
sudo chmod 755 /usr/local/bin/chromedriver
(2) 版本不匹配
# 查看所有可用版本
brew search chromedriver
# 使用 Homebrew 安装指定版本
brew install chromedriver@114
(3) 系统安全限制
# 如果出现 "无法验证开发者"
xattr -d com.apple.quarantine /usr/local/bin/chromedriver
4. 进阶配置
(1) 多版本共存方案
# 创建版本管理目录
mkdir ~/chromedrivers && cd ~/chromedrivers
# 下载不同版本驱动
curl -O https://chromedriver.storage.googleapis.com/114.0.5735.90/chromedriver_mac64.zip
curl -O https://chromedriver.storage.googleapis.com/115.0.5790.170/chromedriver_mac64.zip
# 使用时指定路径
driver = webdriver.Chrome(executable_path='~/chromedrivers/chromedriver_114')
(2) 配置环境变量
# 编辑 ~/.zshrc 或 ~/.bash_profile
export PATH="/usr/local/bin/chromedriver:$PATH"
# 使配置生效
source ~/.zshrc
5. 验证脚本
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument("--headless") # 无头模式
options.add_argument("--disable-gpu")
try:
driver = webdriver.Chrome(options=options)
driver.get("https://www.google.com")
print("✅ ChromeDriver 配置成功!")
print(f"页面标题: {driver.title}")
except Exception as e:
print(f"❌ 配置失败: {str(e)}")
finally:
driver.quit()
维护建议
- 建立版本检查脚本
import requests
from bs4 import BeautifulSoup
def check_update():
url = "https://chromedriver.chromium.org/downloads"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
latest_version = soup.find('a', string=lambda t: t and 'Current Releases' in t).text.split()[-1]
print(f"最新稳定版: {latest_version}")
- 设置自动更新
# 使用 crontab 每周检查更新
0 0 * * 1 curl -s https://chromedriver.storage.googleapis.com/LATEST_RELEASE -o ~/chromedriver_version.txt
通过以上配置,可确保 ChromeDriver 在 macOS 系统上稳定运行,并实现版本自动管理。