使用网页中图片的具体地址下载并保存图片,保存时判断文件是否存在
#定义一个函数参数为图片的地址,以及文件名 def picture (url ,str1): root = '你的存储地址' #图片的存储地址 path = root + str1 + '.jpg' #图片的地址以及名称 try: if not os.path.exists(root): os.mkdir(root) # 如果当前根目录不存在,建立这样一个目录 if not os.path.exists(path): # 判断图片文件是否已经存在 r = requests.get(url) with open(path, 'wb') as f: f.write(r.content) f.close() print('文件保存成功') else: print('文件已存在') except: print('爬取失败')