2

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.

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

Leo Bouloc
  • 302
  • 1
  • 3
  • 16

2 Answers2

7

Preferences for ChromeDriver are an experimental options.

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

For example:

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()

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

For example:

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
)
Oluwafemi Sule
  • 36,144
  • 1
  • 56
  • 81
  • Thank you for your answers. For the first solution, this only partly covers my problem as I am looking for a solution that would block local downloads for all extensions. As for the second solution (/dev/null), I believe that the file is still fetched fully. Is there a way not to download in the case of files being written to disk ? – Leo Bouloc Dec 26 '19 at 21:56
  • 1
    You could set `download_restrictions` option to block all downloads. I was made aware of this option from natn2323 answer. Other configurable options can be found in chrome://prefs-internals – Oluwafemi Sule Dec 26 '19 at 23:37
  • Thank you. This last answer is what I was looking for. – Leo Bouloc Dec 27 '19 at 10:49
1

Another approach that you could take would be disabling the browser's ability to download. Namely, configure the DownloadRestrictions policy, discussed here.

natn2323
  • 1,983
  • 1
  • 13
  • 30