在cron任务中从脚本启动phantomJS

9 投票
3 回答
4254 浏览
提问于 2025-04-18 09:46

我在通过定时任务(cronjob)运行一个Python脚本。我有一个虚拟环境,并且在定时任务中也是通过这个虚拟环境来运行脚本的。当我正常运行这个脚本时,phantomJS会正常启动,但通过定时任务运行时却出现了错误。那么,在定时任务中缺少了什么,导致无法启动phantomJS呢?

Message: 'Unable to start phantomjs with ghostdriver.' ; Screenshot: available via screen
Traceback (most recent call last):
  File "/home/scraper/superfish-extension/chrome_3day.py", line 96, in <module>
    main()
  File "/home/scraper/superfish-extension/chrome_3day.py", line 73, in main
    browser = use_phantomjs()
  File "/home/scraper/superfish-extension/chrome.py", line 81, in use_phantomjs
    browser = webdriver.PhantomJS()
  File "/home/scraper/.virtualenvs/superfish/lib/python2.6/site-packages/selenium/webdriver/phantomjs/webdriver.py", line 50, in __init__
    self.service.start()
  File "/home/scraper/.virtualenvs/superfish/lib/python2.6/site-packages/selenium/webdriver/phantomjs/service.py", line 69, in start
    raise WebDriverException("Unable to start phantomjs with ghostdriver.", e)
WebDriverException: Message: 'Unable to start phantomjs with ghostdriver.' ; Screenshot: available via screen

3 个回答

2

这个方法对我有效:

#!/bin/bash
export DISPLAY=:0
/usr/bin/phantomjs /home/pi/test.js
4

作为一种替代方案,你可以在crontab的第一行添加以下内容:

PHANTOMJS_EXECUTABLE=/usr/local/bin/phantomjs

这行代码是在运行定时任务之前,指定了PhantomJS的路径。

17

因为phantom可能安装在 /usr/local/bin 这个文件夹里,所以你需要把这个文件夹添加到你的crontab的 PATH 里。下面的代码应该可以解决这个问题:

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

撰写回答