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

Docker部署Django项目时Playwright Chromium版本不匹配问题求助

Django + Playwright Chromium Docker集成问题解决

问题现象

  • 配置Dockerfile安装Playwright Chromium后,执行docker-compose up --build调用Playwright功能时,报错找不到/usr/bin/chromium-1067/chrome-linux/chrome可执行文件
  • 容器内实际安装的是chromium-1071,但Playwright始终查找旧版本路径

原因分析

  1. 版本不匹配:Playwright和浏览器版本是绑定的,你先装了Playwright,之后又通过requirements.txt安装了不同版本的Playwright,导致之前装的浏览器版本和新的Playwright不兼容,Playwright依然会找旧版本浏览器的路径。
  2. 环境变量设置时机错误:PLAYWRIGHT_BROWSERS_PATH是在安装Playwright之后才设置的,Playwright初始化时没读到这个路径,后续浏览器装到该路径后,Playwright还是从默认路径找旧版本。
  3. 安装顺序混乱:Dockerfile里先装Playwright,再装requirements.txt的依赖,若requirements里有不同版本的Playwright,会覆盖之前的版本,直接导致浏览器版本和Playwright版本脱节。

正确集成方案

1. 调整Dockerfile安装顺序

把环境变量设置、requirements安装放到Playwright安装前面,确保版本统一:

FROM public.ecr.aws/docker/library/python:3.9
ARG ENVIRONMENT=default
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
# 提前设置浏览器存放路径,让Playwright一开始就识别
ENV PLAYWRIGHT_BROWSERS_PATH=/usr/bin
WORKDIR /app

# 先装系统依赖
RUN apt-get update && apt-get install -y supervisor curl wget gnupg unzip 

# 先装requirements,固定Playwright版本
COPY requirements.txt /app/
RUN pip install --upgrade pip
RUN pip install "setuptools<58.0.0"
RUN pip install -r requirements.txt

# 再装Playwright浏览器依赖和对应版本的Chromium
RUN playwright install-deps chromium
RUN playwright install chromium

# 复制脚本和配置
COPY start-container.sh /usr/local/bin/start-container.sh
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf
RUN chmod +x /usr/local/bin/start-container.sh

COPY . /app/

EXPOSE 80
EXPOSE 5555

ENTRYPOINT ["start-container.sh"]

2. 固定Playwright版本

在requirements.txt里明确写死Playwright版本,比如:

playwright==1.37.0

这样能保证安装的Chromium版本和Playwright完全匹配,不会出现版本错位。

3. 验证容器内状态

启动容器后,进入容器执行以下命令确认:

# 查看Playwright版本
playwright --version
# 查看已安装的浏览器列表和路径
playwright install --list

确保显示的浏览器版本和路径和Playwright版本对应上。

4. 代码中手动指定路径(可选)

如果还是有路径问题,在Django代码里调用Playwright时直接指定浏览器路径:

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    # 替换成容器内实际的Chromium路径
    p.chromium.executable_path = "/usr/bin/chromium-1071/chrome-linux/chrome"
    browser = p.chromium.launch()
    # 后续业务逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 14:56:28