使用 ChromeDriver 和 Selenium 禁用所有下载 [英] Disable all downloads with ChromeDriver and Selenium

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

问题描述

当访问一些静态文件如hudoig.gov/sites/default/files/documents/2016-FW-1007.pdf(随机示例)与 Selenium 使用 ChromeDriver,文件会自动下载到我的默认下载目录.

When accessing some static files such as hudoig.gov/sites/default/files/documents/2016-FW-1007.pdf (random example) with Selenium using ChromeDriver, the file is automatically downloaded to my default download directory.

有没有办法禁用此默认行为并防止文件被保存?谢谢.

Is there a way to disable this default behavior and prevent files from being saved ? Thank you.

注意:我的问题类似于以下未回答的问题,但在我的情况下,即使单击下载链接,我实际上也想禁用下载:有可能使用 selenium 禁用 chrome 中的文件下载

NB: My question is similar to the following unanswered question but in my case I actually want to disable downloads even when clicking download links: Is it possible to disable file download in chrome using selenium

推荐答案

ChromeDriver 的首选项 是一个实验性选项.

您可以明确设置下载偏好并直接在 Chrome 浏览器中打开 PDF 文档.

You could set download preferences explicitly and have PDF documents opened directly in the Chrome browser.

例如:

from selenium import webdriver

options = webdriver.ChromeOptions()

prefs = {
    "download.open_pdf_in_system_reader": False,
    "download.prompt_for_download": True,
    "plugins.always_open_pdf_externally": False
}
options.add_experimental_option(
    "prefs", prefs
)
driver = webdriver.Chrome(
    options=options
)
driver.get(
"https://www.hudoig.gov/sites/default/files/documents/2016-FW-1007.pdf"
)
driver.close()

或者您可以设置下载位置以将文档写入虚拟设备文件,因为 /dev/null 有效地丢弃它.

Or you could set the download location to write the document to a virtual device file as /dev/null effectively discarding it.

例如:

prefs = {
    "download.open_pdf_in_system_reader": False,
    "download.prompt_for_download": True,
    "download.default_directory": "/dev/null",
    "plugins.always_open_pdf_externally": False
}
options.add_experimental_option(
    "prefs", prefs
)

您可以将下载限制设置为阻止所有下载.

You could set download restrictions to block all downloads.

prefs = {
    "download_restrictions": 3,
}
options.add_experimental_option(
    "prefs", prefs
)

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

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