【发布时间】: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