使用Webdriver-manager指定版本下载驱动遇BadZipFile错误求助
问题分析与解决方案
问题本质
报错zipfile.BadZipFile: File is not a zip file说明下载的ChromeDriver文件无效,核心原因是代理配置导致下载内容异常(比如返回代理认证页面、错误页面而非真实驱动压缩包),其次ChromeDriverManager的参数使用需适配3.8.4版本规则。
修复步骤
1. 修复代理配置,确保下载有效驱动包
自定义HttpClient时,需处理代理认证的URL编码,并验证响应内容类型,避免下载非zip文件:
from webdriver_manager.core.http import HttpClient, Response import requests import urllib.parse class CustomHttpClient(HttpClient): def get(self, url, params=None) -> Response: # 对账号密码做URL编码,避免特殊字符破坏代理格式 username = urllib.parse.quote("Login") password = urllib.parse.quote("psw") proxy_url = f"https://{username}:{password}@appxxxx:port" proxies = { 'http': proxy_url, 'https': proxy_url, } response = requests.get(url, params=params, proxies=proxies, verify=False) # 校验响应是否为zip文件,提前拦截错误 if response.headers.get('Content-Type') != 'application/zip': raise ValueError(f"下载内容异常,响应预览:{response.text[:500]}") return Response(response.status_code, response.content, response.headers)
2. 正确设置驱动保存路径
webdriver-manager 3.8.4中path参数指定的是缓存目录,驱动会存放在该目录的子文件夹内。若需直接将驱动放在C:\webDriverDesktop根目录,可在安装后手动复制:
import os import shutil import time import urllib3 from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from webdriver_manager.core.download_manager import WDMDownloadManager os.environ['WDM_SSL_VERIFY'] = '0' urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) PROXY = "https://Login:psw@appxxxx:port" opt = webdriver.ChromeOptions() opt.add_argument('--proxy-server=%s' % PROXY) opt.add_argument("ignore-certificate-errors") # 必须添加该参数指向你的electron应用路径 opt.add_argument("--app=C:\\path\\to\\your\\electronApp.exe") # 初始化自定义客户端与下载管理器 http_client = CustomHttpClient() download_manager = WDMDownloadManager(http_client) # 指定版本与缓存目录 driver_manager = ChromeDriverManager( version="94.0.4606.113", path="C:\\webDriverDesktop", cache_valid_range=1, download_manager=download_manager ) # 安装驱动并获取路径 driver_path = driver_manager.install() # 将驱动复制到目标目录根路径(可选) target_driver_path = os.path.join("C:\\webDriverDesktop", "chromedriver.exe") if not os.path.exists(target_driver_path): shutil.copy(driver_path, target_driver_path) driver_path = target_driver_path # 启动驱动 chrome = webdriver.Chrome(service=Service(driver_path), options=opt) time.sleep(5) chrome.close()
3. 备选:手动下载驱动(规避代理问题)
如果代理问题无法快速解决,可直接手动操作:
- 下载对应版本的ChromeDriver:
chromedriver_win32.zip(版本94.0.4606.113) - 解压到
C:\webDriverDesktop - 代码中直接指定驱动路径,无需
ChromeDriverManager:
chrome = webdriver.Chrome( service=Service("C:\\webDriverDesktop\\chromedriver.exe"), options=opt )
关键注意事项
- 确保代理能正常访问ChromeDriver官方存储源,否则会返回非zip内容
- 针对electron应用,必须通过
--app参数指定应用路径,否则驱动会打开普通Chrome浏览器 - webdriver-manager 3.8.4的
path参数为缓存目录,驱动默认存放在子文件夹,需手动复制到根目录
内容的提问来源于stack exchange,提问作者NabilBLLOUMI
相关产品推荐
相关产品推荐

