Skip to content Skip to sidebar Skip to footer

Download A File (Python 3.4.1 Win8) With No Direct Link To Filename

I wrote the following simple code (with the help of stackoverflow, thanks!) to download a file from a url link: import requests url = 'http://www.url.com/file.pdf' response = reque

Solution 1:

When a browser is given a response with a file, it'll look for the filename as part of the URL, but if there is a Content-Disposition header (originally a MIME header but used in HTTP too) with a filename parameter then the filename is taken from that.

requests doesn't give you any specific assistance; do so yourself instead:

import cgi
from urllib.parse import urlsplit

def filename_from_response(response):
    cdisp = response.headers.get('content-disposition')
    if cdisp:
        _, params = cgi.parse_header(cdisp)
        if 'filename' in params:
            return filename
    last_part = urlsplit(response.url).path.rpartition('/')[-1]
    return last_part

Post a Comment for "Download A File (Python 3.4.1 Win8) With No Direct Link To Filename"