I am trying to download files in Chrome with Selenium. I discovered that headless Chrome does not allow file downloads by default, and applied a workaround. However, implementing the workaround caused some files to produce a Failed - Download Error
in Chrome.
driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': abs_path}}
driver.execute('send_command', params)
Here is what my code looks like:
chrome_options = webdriver.ChromeOptions()
prefs = {
"download.prompt_for_download": False, # allow automatic downloads
"plugins.always_open_pdf_externally": True, # allow download of pdf instead of open in plugin
"download.default_directory": path,
"safebrowsing.enabled": False # allow download of .msi, .exe files, etc.
}
chrome_options.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': path}}
driver.execute('send_command', params)
for url in file_urls: # file_urls here is a list of download links
driver.get(url)
After searching for common reasons for Download error
, things I have ruled out are:
- Incorrect download path: some files with the same download path can be downloaded, but others can
- File path too long: some files that can be downloaded have longer paths than those with errors
After removing the workaround, all files are able to download as per normal, but I would then be unable to download in headless mode. Any suggestions would be helpful.
Additional information:
ChromeDriver version: 2.40.565498
Chrome version: 67.0.3396.87