使用 chrome 无头和硒下载 [英] Downloading with chrome headless and selenium

查看:33
本文介绍了使用 chrome 无头和硒下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python-selenium 和 Chrome 59,并尝试自动化一个简单的下载序列.当我正常启动浏览器时,下载有效,但当我在无头模式下进行时,下载不起作用.

I'm using python-selenium and Chrome 59 and trying to automate a simple download sequence. When I launch the browser normally, the download works, but when I do so in headless mode, the download doesn't work.

# Headless implementation
from selenium import webdriver

chromeOptions = webdriver.ChromeOptions()
chromeOptions.add_argument("headless")

driver = webdriver.Chrome(chrome_options=chromeOptions)

driver.get('https://www.mockaroo.com/')
driver.find_element_by_id('download').click()
# ^^^ Download doesn't start

<小时>

# Normal Mode
from selenium import webdriver

driver = webdriver.Chrome()

driver.get('https://www.mockaroo.com/')
driver.find_element_by_id('download').click()
# ^^^ Download works normally

<小时>

我什至尝试添加默认路径:


I've even tried adding a default path:

prefs = {"download.default_directory" : "/Users/Chetan/Desktop/"}
chromeOptions.add_argument("headless")
chromeOptions.add_experimental_option("prefs",prefs)

添加默认路径在正常实现中是有效的,但同样的问题在无头版本中仍然存在.

Adding a default path works in the normal implementation, but the same problem persists in the headless version.

如何在无头模式下开始下载?

How do I get the download to start in headless mode?

推荐答案

是的,这是一个功能",为了安全.如前所述,这里是错误讨论:https://bugs.chromium.org/p/chromium/issues/detail?id=696481

Yes, it's a "feature", for security. As mentioned before here is the bug discussion: https://bugs.chromium.org/p/chromium/issues/detail?id=696481

Chrome 62.0.3196.0 或更高版本中添加了支持以启用下载.

Support was added in chrome version 62.0.3196.0 or above to enable downloading.

这是一个python实现.我不得不将该命令添加到 chromedriver 命令中.我将尝试提交 PR,以便将来将其包含在库中.

Here is a python implementation. I had to add the command to the chromedriver commands. I will try to submit a PR so it is included in the library in the future.

def enable_download_in_headless_chrome(self, driver, download_dir):
    # add missing support for chrome "send_command"  to selenium webdriver
    driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')

    params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': download_dir}}
    command_result = driver.execute("send_command", params)

作为参考,这里有一个小仓库来演示如何使用它:https://github.com/shawnbutton/PythonHeadlessChrome

For reference here is a little repo to demonstrate how to use this: https://github.com/shawnbutton/PythonHeadlessChrome

update 2020-05-01 有评论说这不再有效.鉴于这个补丁现在已经有一年多了,他们很可能已经改变了底层库.

update 2020-05-01 There have been comments saying this is not working anymore. Given this patch is now over a year old it's quite possible they have changed the underlying library.

这篇关于使用 chrome 无头和硒下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆