如果您只想使用wget 下载东西,何不试试标准python 库中的urllib.urlretrieve?
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()
我没有测试代码,因为我没有找到合适的测试用例。 requests 的一大优势是它还可以处理 authorization。
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)