How to download a file using python in a 'smarter' way?

前端 未结 5 1608
盖世英雄少女心
盖世英雄少女心 2020-11-27 10:04

I need to download several files via http in Python.

The most obvious way to do it is just using urllib2:

import urllib2
u = urllib2.urlopen(\'http:/         


        
5条回答
  •  旧时难觅i
    2020-11-27 10:40

    Combining much of the above, here is a more pythonic solution:

    import urllib2
    import shutil
    import urlparse
    import os
    
    def download(url, fileName=None):
        def getFileName(url,openUrl):
            if 'Content-Disposition' in openUrl.info():
                # If the response has Content-Disposition, try to get filename from it
                cd = dict(map(
                    lambda x: x.strip().split('=') if '=' in x else (x.strip(),''),
                    openUrl.info()['Content-Disposition'].split(';')))
                if 'filename' in cd:
                    filename = cd['filename'].strip("\"'")
                    if filename: return filename
            # if no filename was found above, parse it out of the final URL.
            return os.path.basename(urlparse.urlsplit(openUrl.url)[2])
    
        r = urllib2.urlopen(urllib2.Request(url))
        try:
            fileName = fileName or getFileName(url,r)
            with open(fileName, 'wb') as f:
                shutil.copyfileobj(r,f)
        finally:
            r.close()
    

提交回复
热议问题