

第一种:
def getImage(addr):
u = urllib.urlopen(addr)
data = u.read()
splitPath = addr.split('/')
fName = splitPath.pop()
print fName
f = open(fName, 'wb')
f.write(data)
f.close()
第二种:
def getImage2(addr):
try:
u = urllib2.urlopen(addr)
data = u.read()
splitPath = addr.split('/')
fName = splitPath.pop()
print fName
urllib.urlretrieve(addr, fName)
except Exception,e:
print "[Error]Cant't download: %s:%s" %(fName,e)
使用urllib.urlretrieve(addr, fName) 直接用urllib.urlretrieve获取并保存,fName为保存的文件名,当然可加路径。
def getImage2(addr):
try:
splitPath = addr.split('/')
fName = splitPath.pop()
print fName
open(fName, "wb").write(urllib2.urlopen(addr).read())
except Exception,e:
print "[Error]Cant't download: %s:%s" %(fName,e)
使用urllib2.urlopen,简写方式,其实与第一种一样。
”’python中用作注释,注意也要符合缩进规则。
原创文章,作者:苏葳,如需转载,请注明出处:https://www.swmemo.com/495.html
