python实现图片的批量保存
记录一下关于用python按顺序批量保存图片的学习过程,我想要按顺序保存图片,虽然用idm下载虽然很好,但图片不知道为什么会乱序,就只能自己用python简单实现了一下,对于idm保存图片乱序的问题不知道有没有大神能指点一下,我用的是idm6.4版本。import requestsimport os
#图片批量下载
#author:wuyan
#图片保存路径
save_dirpath = "C:\\Users\\444\\Desktop\\woniu"
#url文本存放路径
url_path = "C:\\Users\\444\\Desktop\\1.txt"
urlList = []
# 从文件中获取图片的url
def get_text(classtxt_path):
urlList = []
with open(classtxt_path,mode='r',encoding='utf-8') as f:
line = f.readline()
while line:
line = line.replace('\n','')
urlList.append(line)
line = f.readline()
return urlList
#保存获取到的图片
def save_image(save_path,request_image):
with open(save_path,mode='wb') as f:
f.write(request_image)
def request_image(Url,save_path):
new_header = {
"user-agent":'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.115 Mobile Safari/537.36',
}
r = requests.get(url=Url,headers=new_header,stream=True)
if r.status_code==200:
save_image(save_path,r.content)
r.close()
return True
return False
#若保存目录不存在便创建它
if not(os.path.exists(save_dirpath)):
os.makedirs(save_dirpath)
print("目录已创建")
urlList =get_text(url_path)
image = 1 #图片编号
status = False #是否成功获取到图片
for url in urlList:
image_path = save_dirpath +"\\"+str(image) + ".jpg"
# print(image_path)
#若不成功则再次重试
while(not(status)):
status=request_image(url,image_path)
print("已保存:"+str(image)+"张")
# print(url)
status =False
image = image + 1
这个还是用得上的,感谢。 很不错,在写论文,学到了 很好的技术,谢谢楼主 感谢大老的教学
页:
[1]