2

次のコードを実行できます。

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 を使用して 1 つのイメージのみを作成する方法についてのアイデアはありますか? ありがとう。

4

3 に答える 3

3

コンテンツをファイルに書き込むだけです:

with open('cow.jpg', 'wb') as f:
    f.write(content)
于 2012-02-19T18:17:17.460 に答える
1

urllibとメソッド urlretrieve を使用します。2 番目の引数はファイルの場所です。

Python 2.x の場合

import urllib
urllib.urlretrieve(URL, path_destination)
于 2012-02-19T18:21:21.627 に答える
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)

このコードには、ファイル全体をメモリに読み込まないという利点があるため、巨大なファイルでも問題なく機能します。それに加えて、サーバーから受信したファイル名と、必要な場合に備えてコンテンツタイプも提供します。

于 2012-02-19T18:16:56.373 に答える