You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker容器中Selenium Chrome Driver无法运行问题求助

解决Docker容器中Selenium Chrome Driver运行报错问题

问题根源

  1. 下载了Windows版本的Chrome包:容器基于Debian Linux系统,需使用对应Linux版本的Chrome浏览器与ChromeDriver,而非win32版本。
  2. 未安装Chrome浏览器本体:Selenium要求Chrome浏览器与ChromeDriver版本严格匹配,仅安装Driver无法正常运行。
  3. ChromeDriver路径未正确配置:解压后的Driver文件未放入系统PATH目录,或缺少可执行权限。
  4. Selenium参数过时:chrome_options在Selenium 3中已被标记为弃用,应使用标准的options参数。

修正后的Dockerfile

FROM python:3.11-slim-buster

# 安装Chrome运行依赖、wget、unzip
RUN apt-get update && apt-get install -y \
    wget unzip \
    libglib2.0-0 libnss3 libgconf-2-4 libfontconfig1 libx11-xcb1 libxcb-dri3-0 \
    libdrm2 libxshmfence1 libgbm1 libasound2 \
    && rm -rf /var/lib/apt/lists/*

# 指定Chrome与ChromeDriver版本(需完全一致)
ARG CHROME_VERSION=128.0.6613.84

# 下载并安装Linux版本Chrome浏览器
RUN wget https://storage.googleapis.com/chrome-for-testing-public/${CHROME_VERSION}/linux64/chrome-linux64.zip \
    && unzip chrome-linux64.zip -d /usr/local/bin/ \
    && ln -s /usr/local/bin/chrome-linux64/chrome /usr/local/bin/chrome \
    && rm chrome-linux64.zip

# 下载并安装对应版本ChromeDriver(Linux版)
RUN wget https://storage.googleapis.com/chrome-for-testing-public/${CHROME_VERSION}/linux64/chromedriver-linux64.zip \
    && unzip chromedriver-linux64.zip -d /usr/local/bin/ \
    && chmod +x /usr/local/bin/chromedriver-linux64/chromedriver \
    && ln -s /usr/local/bin/chromedriver-linux64/chromedriver /usr/local/bin/chromedriver \
    && rm chromedriver-linux64.zip

# 复制项目文件并设置工作目录
COPY . /app
WORKDIR /app

# 安装Python依赖
RUN pip install --no-cache-dir selenium==3.141.0 urllib3==1.26.16 webdriver-manager

# 启动命令
CMD ["python3", "seleniumdriver.py"]

修正后的Python代码

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
# 容器环境必需的Chrome启动参数
chrome_options.add_argument("--headless=new")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")  # 解决容器内存限制问题

# 初始化Driver,使用标准options参数
driver = webdriver.Chrome(options=chrome_options)
try:
    driver.get("https://www.google.com/")
    print("页面加载成功")
finally:
    driver.quit()

构建与运行命令

# 构建Docker镜像
docker build -t seleniumdriver .

# 运行容器
docker run seleniumdriver

关键说明

  • 版本一致性:Chrome浏览器与ChromeDriver必须使用完全相同的版本,否则会触发兼容性错误。
  • 系统依赖补充:slim镜像默认缺少Chrome运行所需的图形库,必须手动安装对应依赖包。
  • 路径配置:通过软链接将Chrome和ChromeDriver放入/usr/local/bin(系统PATH目录),确保Selenium能自动识别可执行文件。
  • 容器专属参数:--no-sandbox和--disable-dev-shm-usage是容器环境下运行Chrome的必需参数,用于规避权限与内存不足问题。

内容的提问来源于stack exchange,提问作者user15069057

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 04:18:13