How do I download a zip file in python using urllib2?

前端 未结 2 1393
孤街浪徒
孤街浪徒 2020-12-05 02:48

Two part question. I am trying to download multiple archived Cory Doctorow podcasts from the internet archive. The old one\'s that do not come into my iTunes feed. I have wr

相关标签:
2条回答
  • 2020-12-05 03:06

    Here's how I'd deal with the url building and downloading. I'm making sure to name the file as the basename of the url (the last bit after the trailing slash) and I'm also using the with clause for opening the file to write to. This uses a ContextManager which is nice because it will close that file when the block exits. In addition, I use a template to build the string for the url. urlopen doesn't need a request object, just a string.

    import os
    from urllib2 import urlopen, URLError, HTTPError
    
    
    def dlfile(url):
        # Open the url
        try:
            f = urlopen(url)
            print "downloading " + url
    
            # Open our local file for writing
            with open(os.path.basename(url), "wb") as local_file:
                local_file.write(f.read())
    
        #handle errors
        except HTTPError, e:
            print "HTTP Error:", e.code, url
        except URLError, e:
            print "URL Error:", e.reason, url
    
    
    def main():
        # Iterate over image ranges
        for index in range(150, 151):
            url = ("http://www.archive.org/download/"
                   "Cory_Doctorow_Podcast_%d/"
                   "Cory_Doctorow_Podcast_%d_64kb_mp3.zip" %
                   (index, index))
            dlfile(url)
    
    if __name__ == '__main__':
        main()
    
    0 讨论(0)
  • 2020-12-05 03:18

    An older solution on SO along the lines of what you want:

    • download a zip file to a local drive and extract all files to a destination folder using python 2.5

    • Python and urllib

    0 讨论(0)
提交回复
热议问题