1.下载图片的两种方法:
1). urllib.request.urlretrieve 方法:方法简单,直接对获取到的图片链接进行下载。
urlretrieve(url,path)
2). requests写入方法:对图片链接进行请求,文件写入时采用‘wb’方式,写入数据为r.content。
r = requests.get(url)
with open(filename, 'wb') as f:
f.write(r.content)
2.实例:百度贴吧图片,共67张图片。
#方法一
import re
import urllib.request
url = "http://tieba.baidu.com/p/2460150866"
response = urllib.request.urlopen(url).read().decode('UTF-8')
##response = urllib.request.urlopen(url).read().decode() #等价于上一句,默认用UTF-8来解码
imglist = re.findall('src="(.+?\.jpg)" pic_ext',response)
x = 0
for imgurl in imglist:
urllib.request.urlretrieve(imgurl,"F:/{}.jpg".format(x)) #远程下载图片
x +=1
print("第",x,"张")
print("Finshed!")
#方法二
import re
import requests
url = "http://tieba.baidu.com/p/2460150866"
r = requests.get(url)
imglist = re.findall('src="(.+?\.jpg)" pic_ext',r.text)
x = 0
for imgurl in imglist:
imgres = requests.get(imgurl)
with open("F:/{}.jpg".format(x),"wb") as f: ##保存图片
f.write(imgres.content)
x +=1
print("第",x,"张")
print("Finshed!")