【发布时间】:2018-11-25 21:43:58
【问题描述】:
我正在尝试使用 Selenium 在 Chrome 中下载文件。我发现无头 Chrome 默认情况下不允许文件下载,并应用了workaround。但是,实施该解决方法会导致某些文件在 Chrome 中生成 Failed - Download Error。
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)
我的代码如下所示:
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)
在搜索了Download error的常见原因后,我排除的事情是:
- 下载路径不正确:有相同下载路径的文件可以下载,有的可以下载
- 文件路径过长:部分可下载文件的路径比有错误的文件路径长
删除解决方法后,所有文件都可以正常下载,但我将无法在无头模式下下载。任何建议都会有所帮助。
附加信息:
ChromeDriver 版本:2.40.565498
Chrome 版本:67.0.3396.87
【问题讨论】:
-
你有没有解决这个问题?我注意到在 not headless 时能够下载的类似问题,但是一旦打开 headless,文件就不会下载。
-
不,这是一项安全功能,我发现的唯一当前解决方案只是对我不起作用的解决方法。我想与此同时,我只需要等待开发人员实现无头下载的功能。
-
我能够使用这个答案让它工作:stackoverflow.com/questions/45631715/…。希望对您有所帮助。
-
我将它应用到我的代码中,一些文件可以下载,但其他文件失败并显示
Download error消息。不过还是谢谢!
标签: python google-chrome selenium