Docker环境下ChromeDriver与Chrome版本不匹配问题求助
解决ChromeDriver与Chrome版本不匹配问题
问题说明
运行Docker镜像时出现错误:
session not created: This version of ChromeDriver only supports Chrome version 114
当前Chrome版本为116.0.5845.96,二进制路径为/usr/bin/google-chrome。
解决方案
方案1:修改Dockerfile安装匹配版本的ChromeDriver
Chrome 115版本之后,ChromeDriver的发布地址和版本获取逻辑发生变化,需调整Dockerfile中的安装步骤:
替换原有ChromeDriver安装代码为:
# Install ChromeDriver(适配Chrome 115+版本) RUN CHROME_VERSION=$(google-chrome --version | grep -oP '\d+\.\d+\.\d+\.\d+') && \ # 获取对应Chrome大版本的最新ChromeDriver版本号 DRIVER_VERSION=$(curl -sSL "https://googlechromelabs.github.io/chrome-for-testing/LATEST_RELEASE_${CHROME_VERSION%%.*}" | grep -oP '\d+\.\d+\.\d+\.\d+') && \ curl -sSL "https://edgedl.me.gvt1.com/edgedl/chrome/chrome-for-testing/${DRIVER_VERSION}/linux64/chromedriver-linux64.zip" -o /chromedriver.zip && \ unzip /chromedriver.zip -d /tmp && \ mv /tmp/chromedriver-linux64/chromedriver /usr/bin && \ chmod +x /usr/bin/chromedriver && \ rm -rf /chromedriver.zip /tmp/chromedriver-linux64
逻辑说明:先获取已安装Chrome的具体版本,再匹配对应大版本的ChromeDriver,从官方新地址下载安装。
方案2:用webdriver-manager自动管理版本
无需手动安装ChromeDriver,通过Python库自动匹配版本:
- 在
requirements.txt中添加依赖:
webdriver-manager
- 修改Selenium连接代码:
from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager def connect_selenium(): options = webdriver.ChromeOptions() options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') options.add_argument('--headless') options.add_argument('--disable-gpu') options.add_argument('--window-size=1920,1080') # 指定Chrome二进制文件路径 options.binary_location = '/usr/bin/google-chrome' # 自动下载并使用匹配版本的ChromeDriver driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options) return driver
此方法会自动检测当前Chrome版本,下载对应ChromeDriver,彻底避免版本不兼容问题。
方案3:锁定Chrome版本(可选)
如果需要固定环境版本,可在Dockerfile中指定安装特定版本的Chrome:
# Install specific version of Chrome RUN curl -sSL https://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-stable/google-chrome-stable_116.0.5845.96-1_amd64.deb -o /chrome.deb RUN dpkg -i /chrome.deb || apt-get install -fy
随后安装对应版本的ChromeDriver即可保持版本完全匹配。
内容的提问来源于stack exchange,提问作者viet
相关产品推荐
相关产品推荐

