Download content-disposition from http response header (Python 3)

梦想的初衷 提交于 2021-02-19 05:03:58

问题


Im looking for a little help here. I've been using requests in Python to gain access to a website. Im able access the website and get a response header but im not exactly sure how to download the zip file contained in the Content-disposition. Im guessing this isnt a function Requests can handle or at least I cant seem to find any info on it. How do I gain access to the file and save it?

'Content-disposition': 'attachment;filename=MT0376_DealerPrice.zip'

回答1:


Using urllib instead of requests because it's a lighter library :

import urllib

req = urllib.request.Request(url, method='HEAD')
r = urllib.request.urlopen(req)
print(r.info().get_filename())

Example :

In[1]: urllib.request.urlopen(urllib.request.Request('https://httpbin.org/response-headers?content-disposition=%20attachment%3Bfilename%3D%22example.csv%22', method='HEAD')).info().get_filename()
Out[1]: 'example.csv'



回答2:


What you want to do is to access response.content. You may want to add better checks if the content really contains the file.

Little example snippet

response = requests.post(url, files={'name': 'filename.bin'}, timeout=60, stream=True)
if response.status_code == 200:
    if response.headers.get('Content-Disposition'):
        print("Got file in response")
        print("Writing file to filename.bin")
        open("filename.bin", 'wb').write(response.content)


来源:https://stackoverflow.com/questions/28311735/download-content-disposition-from-http-response-header-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!