@DebanjanB 的答案是正确的,但不清楚。
在解决问题和总结解决方案后:
问题:运行 selenium,但出错
代码:
from selenium import webdriver
chromeOptions = webdriver.ChromeOptions()
chromeOptions.add_argument('--headless’)
driver = webdriver.Chrome(options=chromeOptions)
运行但出错:
selenium.common.exceptions.WebDriverException: 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.)
原因
-
直接原因
-
unknown error: DevToolsActivePort file doesn't exist 表示 ChromeDriver 生成 WebBrowser(Chrome 浏览器会话)失败
-
根本原因
解决方案
(推荐)正确解决方案
使用普通用户运行 Chrome
如何使用普通用户运行chrome?
我的情况:在 CentOS 中
(1) 将 chrome 二进制文件更改为普通用户拥有的
sudo chown limao:limao /opt/google/chrome/google-chrome
注意:这里的chrome二进制是/usr/bin/google-chrome,经过几次软链接到真正的一个是/opt/google/chrome/google-chrome
更改所有者后:
limao@localhost:~/dev/ShortLinkParseServer/logs $ ll /usr/bin/google-chrome
lrwxrwxrwx 1 root root 31 Aug 4 16:30 /usr/bin/google-chrome -> /etc/alternatives/google-chrome
limao@localhost:~/dev/ShortLinkParseServer/logs $ ll /etc/alternatives/google-chrome
lrwxrwxrwx 1 root root 29 Aug 4 16:30 /etc/alternatives/google-chrome -> /usr/bin/google-chrome-stable
limao@localhost:~/dev/ShortLinkParseServer/logs $ ll /opt/google/chrome/google-chrome
-rwxr-xr-x 1 limao limao 1.9K Jul 31 04:46 /opt/google/chrome/google-chrome
(2) 为 supervisord spawn 程序设置普通用户
将user=xxx 添加到您的supervisord config file 中,如下所示:
$ cat /etc/supervisord.d/supervisord_ShortLinkParseServer.conf
[program:ShortLinkParseServer]
command=/xxx/gunicorn/gunicorn_config.py app:app
...
; use normal user instead default root use, to avoid later chrome exception: unknown error: DevToolsActivePort file doesn't exist
user=limao
...
解决方案(待验证)
添加标志--disable-dev-shm-usage
chromeOptions.add_argument('--disable-dev-shm-usage')
错误的解决方案
太多人使用这个:添加标志--no-sandbox
但--no-sandbox 只是表示不使用沙盒
->真正的效果只是绕过操作系统安全模型
-> 如此高度不推荐使用--no-sandbox