を使用して何かをダウンロードするだけの場合は、標準のPythonライブラリでurllib.urlretrievewget
を試してみませんか?
import os
import urllib
image_url = "https://www.google.com/images/srpr/logo3w.png"
image_filename = os.path.basename(image_url)
urllib.urlretrieve(image_url, image_filename)
編集:画像がスクリプトによって動的にリダイレクトされる場合は、requests
パッケージを試してリダイレクトを処理することができます。
import requests
r = requests.get(image_url)
# here r.url will return the redirected true image url
image_filename = os.path.basename(r.url)
f = open(image_filename, 'wb')
f.write(r.content)
f.close()
適切なテストケースが見つからないため、コードをテストしていません。の大きな利点の1つは、承認requests
も処理できることです。
EDIT2 :画像がGravatar画像のようにスクリプトによって動的に提供される場合、通常、応答ヘッダーのcontent-disposition
フィールドでファイル名を見つけることができます。
import urllib2
url = "http://www.gravatar.com/avatar/92fb4563ddc5ceeaa8b19b60a7a172f4"
req = urllib2.Request(url)
r = urllib2.urlopen(req)
# you can check the returned header and find where the filename is loacated
print r.headers.dict
s = r.headers.getheader('content-disposition')
# just parse the filename
filename = s[s.index('"')+1:s.rindex('"')]
f = open(filename, 'wb')
f.write(r.read())
f.close()
EDIT3:@Alexがコメントで示唆しているように、返されたヘッダーでエンコードされたものをサニタイズする必要があるかもしれませんfilename
。ベース名を取得するだけで問題ないと思います。
import os
# this will remove the dir path in the filename
# so that `../../../etc/passwd` will become `passwd`
filename = os.path.basename(filename)