DigitalOcean Droplet部署Django+Selenium遇chromedriver异常退出问题
解决方案
1. 排查Gunicorn运行用户的权限问题
直接运行脚本或runserver用的是当前登录用户(比如root或你的个人普通用户),但Gunicorn默认常以www-data这类系统用户启动,该用户可能没有Chrome/Chromedriver的执行权限。
- 解决方式:
- 修改Gunicorn的service配置文件,指定用能正常运行脚本的用户启动,比如在配置里添加
User=你的用户名 - 或者给
www-data用户赋予相关权限:sudo chmod +x /usr/bin/chromedriver sudo chown -R www-data:www-data /usr/bin/google-chrome
- 修改Gunicorn的service配置文件,指定用能正常运行脚本的用户启动,比如在配置里添加
2. 强制配置Chrome无头模式及必要参数
服务器是无图形界面环境,Gunicorn运行时没有DISPLAY变量,必须明确配置Chrome的无头参数,修改automation.py里的驱动初始化代码:
from selenium import webdriver from selenium.webdriver.chrome.options import Options def get_chrome_driver(): chrome_options = Options() # 核心无头模式参数 chrome_options.add_argument('--headless=new') chrome_options.add_argument('--no-sandbox') # 规避权限限制 chrome_options.add_argument('--disable-dev-shm-usage') # 解决临时空间不足问题 chrome_options.add_argument('--disable-gpu') # 服务器无需GPU加速 # 明确指定Chrome和Chromedriver路径 chrome_options.binary_location = '/usr/bin/google-chrome' driver = webdriver.Chrome(executable_path='/usr/bin/chromedriver', options=chrome_options) return driver
3. 对齐Gunicorn与本地运行的环境变量
Gunicorn的运行环境变量和你直接执行脚本的环境可能不一致,比如PATH未包含Chrome路径,或缺少DISPLAY变量。
- 解决方式:在Gunicorn的service配置文件中添加环境变量:
之后重启Gunicorn:Environment="PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" Environment="DISPLAY=:0"sudo systemctl restart gunicorn
4. 查看Chromedriver详细日志定位问题
默认错误信息不够具体,给Chromedriver指定日志路径获取详细报错:
from selenium.webdriver.common.service import Service service = Service('/usr/bin/chromedriver') service.log_path = '/var/log/chromedriver.log' driver = webdriver.Chrome(service=service, options=chrome_options)
查看日志内容:cat /var/log/chromedriver.log,根据日志里的具体提示(比如缺失依赖库、权限不足)针对性解决。
5. 验证Chrome在Gunicorn用户下的可运行性
切换到Gunicorn的运行用户,手动测试Chrome是否能正常启动:
sudo su - www-data -s /bin/bash google-chrome --headless=new --no-sandbox --disable-dev-shm-usage --dump-dom https://google.com
如果该命令报错,说明Chrome本身在该用户下无法运行,需安装缺失的依赖(比如libxss1、libappindicator3-1等)。
内容的提问来源于stack exchange,提问作者Sakib ovi
相关产品推荐
相关产品推荐

