Py下载指定路径下所有图片
[代码]:
import re
import os
import urllib.request
url = "image.baidu.com/search/inde…"
save_path = r'E:\img\ppp' #r 字符串不转义
if not os.path.isdir(save_path): #文件夹不存在就创建
os.mkdir(save_path)
response = urllib.request.urlopen(url)
html = response.read()
html = html.decode('utf-8') #指定的编码格式解码字符串
#或链式连接
#html = urllib.request.urlopen(url).read().decode('utf-8')
reg = r'"objURL":"(.*?)"' #正则获取图片url路径
imgre = re.compile(reg)
imglist = re.findall(imgre, html)
#下载图片
x = total = 0
for imgurl in imglist:
print('Exec: ',imgurl)
total += 1
filename = os.path.join(save_path,str(x)+'.jpg') #拼接图片的全路径
try: #try except判断图片是否能打开,不管能不能打开都继续下一次循环
res = urllib.request.urlopen(imgurl)
if str(res.status) != '200':
print("Error:can't open!")
continue
except Exception as e:
print(e)
continue
#下载图片 with open 下载 或 urlretrieve下载
'''
with open(filename, 'wb') as f: #以二进制写模式打开
f.write(res.read())
print("Succe: %s \n" % filename)
x += 1
'''
urllib.request.urlretrieve(imgurl, filename)
print("Succe: %s \n" % filename)
x += 1
print("End:Total[ %s ];Success[ %s ]" % (total, x) )