【问题标题】:Python webdriver script OK from console but won't start as an Upstart servicePython webdriver 脚本可以从控制台运行,但不会作为 Upstart 服务启动
【发布时间】:2017-07-11 13:04:18
【问题描述】:

我需要运行一个使用 Selenium webdriver 的 Python 脚本:

import platform
from selenium import webdriver
from pyvirtualdisplay import Display

driver = None

if platform.system() == 'Linux':
    print("Initializing browser for chrome...")
    DISPLAY = Display(visible=0, size=(800, 600))
    DISPLAY.start()
    print("Started display")
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--no-sandbox')
    driver = webdriver.Chrome('/usr/local/bin/chromedriver', chrome_options=chrome_options)
    print("Done init chrome")
    connected = True
else:
    try:
        print("Starting firefox...")
        driver = webdriver.Firefox()
        connected = True
    except:
        print("Could not connect through firefox")

if driver:
    print("driver ok")
    driver.quit()
    print("All ok")

脚本从控制台运行正常:

sudo ~/environments/scrapers/bin/python test_webdriver.py
Initializing browser for chrome...
Started display
Done init chrome
driver ok
All ok

但如果尝试使用带有 Upstart 的 exec 节运行,则会出现 WebDriverException 错误:

Initializing browser for chrome...
Started display
...
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
  (Driver info: chromedriver=2.26.436382 (70eb799287ce4c2208441fc057053a5b07ceabac),platform=Linux 4.8.0-58-generic x86_64)

我在 upstart 脚本中添加了可能不存在的路径,像这样

env PYTHON_HOME=/home/rsa-key-20161031/environments/scrapers
env PATH=/usr/local/bin:/usr/bin:$PYTHON_HOME:$PATH
env ENV=production
env DISPLAY=:10
chdir /home/user/project
console log
exec $PYTHON_HOME/bin/python test_webdriver.py

没有效果。搜索错误并没有给出任何具体的信息。 非常感谢任何有关如何使这项工作发挥作用的见解。

更新: 我目前的解决方案是使用 Cron,因为使用 Xvfb 似乎没有问题。我仍然非常想知道是否可以将 webdriver 任务作为服务运行。我还尝试使用 Selenium 作为远程 webdriver,结果相同(Chrome 显然无法连接到虚拟显示器后退出)

【问题讨论】:

  • Upstart 没有用于启动 Chrome 的 X-Windows 会话。 Upstart 和其他 Linux 服务管理系统(systemd、sysVinit)不适合与依赖 GUI 的服务一起使用。
  • 谢谢;我使用 Pyvirtualdisplay/start Xvfb 作为一个单独的进程这一事实有什么改变吗?

标签: python linux bash selenium-webdriver upstart


【解决方案1】:

我遇到了类似的情况,而我将 pytest 配置为使用 selenium 和 firefox webdriver 运行。

作为一种解决方案,您可以安装 xvfb,即在 debian 中

sudo apt install xvfb

现在您可以在 exec 位置之后调整您的新贵文件,以便使用您的脚本作为参数调用 xvfb

xvfb-run --server-num=10 <script>

这样xvfb 在你的脚本前面开始。

【讨论】:

  • 好主意,谢谢;在尝试这个时;启动时 Xvfb-run 给出以下错误:/usr/bin/xvfb-run: mktemp: not found,而系统中存在 mktemp。对此有什么想法吗?
  • @AlexBausk 很高兴听到它几乎可以工作。我猜mktemp 不是您的 PATH 变量的一部分;所以输入which mktemp(在我的情况下为/bin)并添加带有冒号的路径,即env PATH=/bin:/usr/local/bin:...
  • 哇,它现在确实有效。我非常感谢您的帮助!这一直困扰着我
猜你喜欢
  • 2016-10-04
  • 2016-04-04
  • 2017-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-06
  • 2018-04-14
  • 1970-01-01
相关资源
最近更新 更多