Render部署Selenium/Flask/Docker脚本遇WebDriverException求助
解决Render平台部署Selenium爬虫时WebDriverException(状态码127)的问题
错误原因
状态码127表明chromedriver无法正常启动,核心问题是你使用的python:3.9-slim轻量镜像未安装Chrome浏览器本身,同时缺少Chrome运行必需的系统依赖库。Selenium的chromedriver只是驱动程序,必须搭配对应版本的Chrome浏览器才能工作。
解决方案
1. 修改Dockerfile,安装Chrome及系统依赖
替换原Dockerfile为以下内容,确保镜像中包含完整的Chrome环境:
FROM python:3.9-slim WORKDIR / # 安装Chrome运行所需的系统依赖库 RUN apt-get update && apt-get install -y \ wget \ gnupg \ unzip \ fonts-liberation \ libasound2 \ libatk-bridge2.0-0 \ libatk1.0-0 \ libc6 \ libcairo2 \ libcups2 \ libdbus-1-3 \ libexpat1 \ libfontconfig1 \ libgbm1 \ libgcc1 \ libglib2.0-0 \ libgtk-3-0 \ libnspr4 \ libnss3 \ libpango-1.0-0 \ libpangocairo-1.0-0 \ libstdc++6 \ libx11-6 \ libx11-xcb1 \ libxcb1 \ libxcomposite1 \ libxcursor1 \ libxdamage1 \ libxext6 \ libxfixes3 \ libxi6 \ libxrandr2 \ libxrender1 \ libxss1 \ libxtst6 \ lsb-release \ wget \ xdg-utils \ && rm -rf /var/lib/apt/lists/* # 安装Chrome浏览器 RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \ && echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list \ && apt-get update && apt-get install -y google-chrome-stable \ && rm -rf /var/lib/apt/lists/* COPY requirements.txt requirements.txt RUN pip install --no-cache-dir -r requirements.txt COPY . . ENV PORT=5000 EXPOSE $PORT CMD ["python", "wiki_script.py"]
2. 优化Selenium初始化代码
在wiki_script.py的Chrome配置中添加Chrome二进制路径,并使用新版无头模式提升稳定性:
chrome_options = Options() chrome_options.add_argument("--headless=new") # 新版无头模式,兼容性更强 chrome_options.add_argument("user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.6422.60 Safari/537.36") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--window-size=1920,1080") chrome_options.binary_location = "/usr/bin/google-chrome" # 指定Chrome二进制文件路径 driver = webdriver.Chrome(options=chrome_options)
3. 其他注意事项
- 确保
requirements.txt中的selenium版本与安装的Chrome版本兼容(当前Chrome稳定版对应Selenium 4.x版本,你的配置已满足) - Render平台部署时,建议使用
gunicorn作为生产服务器,可将Dockerfile的CMD改为:CMD ["gunicorn", "--bind", "0.0.0.0:$PORT", "wiki_script:app"],避免使用Flask自带的调试服务器
内容的提问来源于stack exchange,提问作者cd91
相关产品推荐
相关产品推荐

