python - 使用 crontab (python) 运行 selenium

标签 python ubuntu selenium crontab

我有一个 python 脚本,它在下一行通过 selenium 调用 chrome。

 ff = webdriver.Chrome('/home/user01/webScraping/CollectAndGo/chromedriver')

python 脚本是从 shell 脚本调用的。

python /home/user01/webScraping/CollectAndGo/cgcom.py > /home/user01/webScraping/CollectAndGo/cgcom.log 2>&1

当我从终端运行脚本或仅执行 .sh 文件时,它运行良好,但当我安排 crontab 作业时,它失败并出现下一个错误。

   raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: u'unknown error: Chrome failed to start: exited abnormally\n  (Driver info: chromedriver=2.9.248304,platform=Linux 3.5.0-36-generic x86_64)' 

错误与本题第一行代码有关。有人知道为什么会这样吗?

最佳答案

尝试从 cron 启动浏览器时最明显的问题是,即使您的机器上正在运行 X,DISPLAY 环境变量也没有为进程设置从您的 crontab 运行,因此从那里启动浏览器将失败。

解决方案范围从琐碎到 super 复杂。一个简单的解决方案是接受如果没有 X 运行则您的脚本将不会运行并手动将 DISPLAY 设置为 :0,这是Ubuntu 启动的默认 X 服务器。

例如,如果我将此命令放在 crontab 行的 command 列中,Chrome 会正常启动:

DISPLAY=:0 google-chrome

用户特定的 crontab 文件中的完整行类似于:

0 * * * *  DISPLAY=:0 google-chrome

如果你想运行一个通过 selenium 启动 chrome 的 python 脚本,该行将如下所示:

0 * * * *  DISPLAY=:0 python my_script.py

命令字符串按原样发送到 shell,因此在最后一个示例中,字符串 DISPLAY=:0 python my_script.py 将只传递到 shell。将在命令开始时立即给出的变量赋值解释为设置环境变量是常见的 shell 语法。 (dashbash 肯定是这种情况,其中之一很可能是大多数安装中的默认 shell。)所以 shell 解释的命令设置了环境变量 DISPLAY 的值 :0 然后运行 ​​python my_script.py。由于 python 从启动它的 shell 继承了它的环境,变量 DISPLAY 对它来说也是 :0

像我上面显示的那样设置 DISPLAY=:0 为后面的命令设置变量 only 。对于 crontab 执行的所有命令,也可以将 DISPLAY 设置为 :0。例如在以下用户特定的 crontab 中:

DISPLAY=:0

30 * * * *  google-chrome
0  * * * *  python my_script.py

DISPLAY=:0 设置环境变量 DISPLAY 以执行 google-chromepython my_script。 py

关于python - 使用 crontab (python) 运行 selenium,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23908319/

相关文章:

ubuntu - 捕获当前正在运行的程序作为启动程序

ubuntu - 找不到 libreoffice 的源包

python - 如何在 ubuntu 16.04 上为 python3 selenium 安装 firefoxdriver webdriver?

java - cucumber .runtime.CucumberException : Couldn't load plugin class: json-pretty with Cucumber Selenium and Java

python - 尝试将文件加载到 Python 中,但它声明它不存在,即使它确实存在

python - 从 dict 解析嵌套键(从 json 生成)

python - Python argparse 中的手动命令规范

java - Eclipse 不启动 (Ubuntu) : JVM terminated. 退出代码=13

python - 如何有效地改变数组中一定数量的值?

python - ChromeDriver 假设 Chrome 在传递配置文件参数时崩溃了