gpt4 book ai didi

Python webdriver 脚本可以从控制台运行,但不会作为 Upstart 服务启动

转载 作者:太空宇宙 更新时间:2023-11-04 10:18:25 25 4
gpt4 key购买 nike

我需要运行一个使用 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 作为远程网络驱动程序,但结果相同(Chrome 在显然无法连接到虚拟显示器后退出)

最佳答案

当我将 pytest 配置为与 selenium 和 firefox webdriver 一起运行时,我遇到了类似的情况。

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

sudo apt install xvfb

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

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

这样 xvfb 在您的脚本前启动。

关于Python webdriver 脚本可以从控制台运行,但不会作为 Upstart 服务启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45035433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com