Search code examples
pythondownloadurllib2urllib

Python download without supplying a filename


How do I download a file with progress report using python but without supplying a filename.

I have tried urllib.urlretrieve but I seem to have to supply a filename for the downloaded file to save as.

So for example:

I don't want to supply this:

urllib.urlretrieve("http://www.mozilla.com/products/download.html?product=firefox-3.6.3&os=win&lang=en-US", "/tmp/firefox.exe")

just this:

urllib.urlretrieve("http://www.mozilla.com/products/download.html?product=firefox-3.6.3&os=win&lang=en-US", "/tmp/")

but if I do I get this error:

IOError: [Errno 21] Is a directory: '/tmp'

Also unable to get the filename from some URL Example:

http://www.mozilla.com/products/download.html?product=firefox-3.6.3&os=win&lang=en-US


Solution

  • Here is a complete way to do it with python3 and no filename specified in the url:

    from urllib.request import urlopen, urlretrieve
    import cgi
    
    url = "http://cloud.ine.ru/s/JDbPr6W4QXnXKgo/download"
    remotefile = urlopen(url)
    contentdisposition = remotefile.info()['Content-Disposition']
    _, params = cgi.parse_header(contentdisposition)
    filename = params["filename"]
    urlretrieve(url, filename)
    

    In the result you should get cargo_live_animals_parrot.jpg file