如何使用python&#s; httplib2保存文件?

时间:2012-02-19 18:12:21

标签: python httplib2

我可以运行以下代码:

import httplib2

h = httplib2.Http('.cache')

response, content = h.request('http://2.bp.blogspot.com/-CXFfl9luHPM/TV-Os6opQfI/AAAAAAAAA2E/oCgrgvWqzrY/s1600/cow.jpg')

print(response.status)

with open('cow.jpg', 'wb') as f:
    f.write(content)

当我运行代码时,我下载了一个名为cow.jpg的文件,这是我想要的,但我也得到了一个名为的复制图像:2.bp.blogspot.com,-CXFfl9luHPM,TV-Os6opQfI ,AAAAAAAAA2E,oCgrgvWqzrY,S1600,cow.jpg,77ba31012a25509bfdc78bea4e1bfdd1。这是带有逗号和其他垃圾的http地址。关于如何使用httplib2只创建一个图像的任何想法?感谢。

3 个答案:

答案 0 :(得分:3)

只需将内容写入文件:

with open('cow.jpg', 'wb') as f:
    f.write(content)

答案 1 :(得分:1)

使用urllib和方法urlretrieve,第二个参数是文件位置。

for python 2.x

import urllib
urllib.urlretrieve(URL, path_destination)

答案 2 :(得分:0)

也正在使用urllib2吗?如果是,您可以使用此功能:

def download_file(url):
    """Create an urllib2 request and return the request plus some useful info"""
    name = filename_from_url(url)
    r = urllib2.urlopen(urllib2.Request(url))
    info = r.info()
    if 'Content-Disposition' in info:
        # If the response has Content-Disposition, we take filename from it
        name = info['Content-Disposition'].split('filename=')[1]
        if name[0] == '"' or name[0] == "'":
            name = name[1:-1]
    elif r.geturl() != url:
        # if we were redirected, take the filename from the final url
        name = filename_from_url(r.geturl())
    content_type = None
    if 'Content-Type' in info:
        content_type = info['Content-Type'].split(';')[0]
    # Try to guess missing info
    if not name and not content_type:
        name = 'unknown'
    elif not name:
        name = 'unknown' + mimetypes.guess_extension(content_type) or ''
    elif not content_type:
        content_type = mimetypes.guess_type(name)[0]
    return r, name, content_type

用法:

fp, filename, content_type = download_file('http://url/to/some/file')
with open('somefile', 'w') as dst:
    shutil.copyfileobj(fp, dst)

此代码的优点是永远不会将整个文件读入内存 - 因此它也适用于大型文件。除此之外,它还为您提供从服务器收到的文件名和内容类型(如果您需要/需要它)。

相关问题