簡體   English   中英

如何使用python的httplib2保存文件?

[英]How do I save a file using python's 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僅創建一個映像的任何想法? 謝謝。

只需將內容寫入文件:

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

使用urllib和urlretrieve方法,第二個參數是文件位置。

對於python 2.x

import urllib
urllib.urlretrieve(URL, path_destination)

您也可以使用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)

該代碼的優點是永遠不會將整個文件讀入內存-因此,它對於大型文件也能正常工作。 除此之外,它還為您提供了從服務器接收的文件名和內容類型(如果需要)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM