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

Linux服务器Selenium无头模式运行失败:DevToolsActivePort文件不存在

问题解决:Selenium Chrome无头模式在Django+Nginx环境下启动失败

错误信息

Message: unknown error: Chrome failed to start: exited abnormally.
(unknown error: DevToolsActivePort file doesn't exist)
(The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)

可能的解决方案

1. 补全Chrome无头模式启动参数

本地运行正常但服务环境下失败,核心原因往往是启动参数不全。确保添加以下关键参数:

from selenium.webdriver.chrome.options import Options

options = Options()
# 新版无头模式(替代旧--headless,兼容性更强)
options.add_argument("--headless=new")
# 禁用沙箱(非root用户运行Chrome必需)
options.add_argument("--no-sandbox")
# 规避/dev/shm内存不足导致的崩溃
options.add_argument("--disable-dev-shm-usage")
# 指定调试端口,解决DevToolsActivePort不存在问题
options.add_argument("--remote-debugging-port=9222")
# 禁用GPU(服务器环境无GPU硬件)
options.add_argument("--disable-gpu")
# 明确指定Chrome二进制文件路径
options.binary_location = "/usr/bin/google-chrome"

2. 检查Django服务运行用户的权限

Nginx/uWSGI/Gunicorn通常以www-data或其他非root用户运行,需确保该用户:

  • 拥有/usr/bin/google-chrome和ChromeDriver的执行权限
  • 对临时目录(如/tmp)有读写权限,也可手动指定专属用户数据目录:
    options.add_argument("--user-data-dir=/var/tmp/chrome-user-data")
    
    然后给该目录赋予服务用户权限:
    sudo chown -R www-data:www-data /var/tmp/chrome-user-data
    

3. 安装Chrome依赖库

服务器可能缺少Chrome运行必需的系统依赖,以Ubuntu/Debian为例执行:

sudo apt-get update && sudo apt-get install -y libxss1 libappindicator1 libindicator7 libnss3 libasound2 libatk-bridge2.0-0 libgtk-3-0

4. 明确指定ChromeDriver路径

不要依赖$PATH环境变量,直接在代码里指定ChromeDriver的绝对路径:

from selenium.webdriver.chrome.service import Service

service = Service(executable_path="/usr/local/bin/chromedriver") # 替换为你的实际路径
driver = webdriver.Chrome(service=service, options=options)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 07:22:33