Reputation: 311
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
Upvotes: 3
Views: 8907
Reputation: 38952
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
)
Upvotes: 9