在CentOS7上,使用Selenium和Chromedriver编写的Python脚本在无界面模式下手动调用时可以正常运行。
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('no-sandbox')
self.driver = webdriver.Chrome(chrome_options=options)
当使用crontab启动脚本时,它会在第4行(如上所示)抛出此异常。完整的回溯信息请见底部。
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.38.552522
Cron是使用crontab -e设置的
* * * * * cd /to/path && /to/path/.virtualenvs/selenium/bin/python /to/path/script.py -t arg1 arg2 > /to/path/log.txt 2>&1
这导致出现了像 chromedriver 找不到的错误。然后我添加了以下内容到 crontab -e 中。
1) 使用 bash 而不是 sh,虽然在 sh 中手动启动 python 脚本可以正常工作
2) 指定 chromedriver 的路径。
SHELL=/bin/bash
PATH=/usr/local/bin/
我尝试了一些网络上的建议,例如在我的脚本中添加--no-sandbox选项以解决问题。但是这些方法都没有起到帮助作用。请注意,我正在使用chrome无头模式,因此我认为在cron中不需要导出DISPLAY=:0或Xvfb库等内容。
Python 3.6.1 Selenium 3.4.3 Chromedriver 2.38.552522 google-chrome-stable 65.0.3325.181
完整的回溯信息
Exception in thread <name>:
Traceback (most recent call last):
File "/usr/lib64/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/lib64/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/path/to/script.py", line 53, in start
self.site_scrape(test_run)
File "/path/to/script.py", line 65, in site
self.driver = webdriver.Chrome(chrome_options=options)
File "/home/<user>/.virtualenvs/selenium/lib64/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py", line 69, in __init__
desired_capabilities=desired_capabilities)
File "/home/<user>/.virtualenvs/selenium/lib64/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 98, in __init__
self.start_session(desired_capabilities, browser_profile)
File "/home/<user>/.virtualenvs/selenium/lib64/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 188, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "/home/<user>/.virtualenvs/selenium/lib64/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 256, in execute
self.error_handler.check_response(response)
File "/home/<user>/.virtualenvs/selenium/lib64/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
(Driver info: chromedriver=2.38.552522 (437e6fbedfa8762dec75e2c5b3ddb86763dc9dcb),platform=Linux 4.14.12-x86_64-linode92 x86_64)
crontab -u
指定用户,并确保你的 chromedriver 可执行文件权限正确吗? - ekostadinovcrontab -u <user> -l
shows the correct cron entry. chromedriver has following permissions-rwxr-xr-x 1 root root 7872560 Mar 2 02:19 chromedriver
- Jim B2.37
和2.38
版本的chromedriver,因为两者都支持您的浏览器版本。 - ekostadinovselenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.38.552522)
。 - Jim B