【问题标题】:How do I download a zip file in python using urllib2?如何使用 urllib2 在 python 中下载 zip 文件?
【发布时间】:2011-05-01 00:46:03
【问题描述】:

两部分问题。我正在尝试从 Internet 存档下载多个存档的 Cory Doctorow 播客。旧的没有进入我的 iTunes 提要。我已经编写了脚本,但是下载的文件格式不正确。

Q1 - 下载 zip mp3 文件需要做些什么更改? Q2 - 将变量传递到 URL 的更好方法是什么?

 # and the base url.

def dlfile(file_name,file_mode,base_url):
    from urllib2 import Request, urlopen, URLError, HTTPError

    #create the url and the request
    url = base_url + file_name + mid_url + file_name + end_url 
    req = Request(url)

    # Open the url
    try:
        f = urlopen(req)
        print "downloading " + url

        # Open our local file for writing
        local_file = open(file_name, "wb" + file_mode)
        #Write to our local file
        local_file.write(f.read())
        local_file.close()

    #handle errors
    except HTTPError, e:
        print "HTTP Error:",e.code , url
    except URLError, e:
        print "URL Error:",e.reason , url

# Set the range 
var_range = range(150,153)

# Iterate over image ranges
for index in var_range:

    base_url = 'http://www.archive.org/download/Cory_Doctorow_Podcast_'
    mid_url = '/Cory_Doctorow_Podcast_'
    end_url = '_64kb_mp3.zip'
    #create file name based on known pattern
    file_name =  str(index) 
    dlfile(file_name,"wb",base_url

此脚本改编自here

【问题讨论】:

    标签: python urllib2


    【解决方案1】:

    以下是我处理 url 构建和下载的方式。我确保将文件命名为 url 的基本名称(斜杠后的最后一位),并且我还使用 with 子句打开要写入的文件。这使用了ContextManager,这很好,因为它会在块退出时关闭该文件。此外,我使用模板来构建 url 的字符串。 urlopen 不需要请求对象,只需要一个字符串。

    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()
    

    【讨论】:

    • 最后一个问题,我在哪里可以了解有关 URL 中使用的“%d”的更多信息,我仍然对它的工作原理有点粗略。
    • 查看文档以了解字符串格式:docs.python.org/library/stdtypes.html#string-formatting
    • 此方法的一个缺点是f.read() 会将整个文件存储在内存中,然后再将其写入磁盘,如果文件太大,可能会失败。
    【解决方案2】:
    猜你喜欢
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多