Python爬虫入门——爬取网页图片

内容整理自中国大学MOOC——北京理工大学-蒿天-Python网络爬虫与信息提取

利用requests.get()方法爬取网页图片,并保存至本地

1 import requests
2 
3 path = "D:/picture.jpg"  #设定保存路径
4 url = "http://img.kitstown.com/news/2020/01/20psg4th.jpg"  #web图片路径
5 r = requests.get(url)
6 print(r.status_code)
7 with open(path,"wb") as f:
8     f.write(r.content)  #将返回的二进制内容写入文件(实际就是将图片爬取至本地)

对于代码进行进一步优化,使保存在本地的文件名与原始文件名相同,并加入异常提醒

import requests
 import os
 url = "http://img.kitstown.com/news/2020/01/20psg4th.jpg"
 root = "D://pics//"  #设置保存目录
 path = root + url.split('/')[-1]  #将图片的原始文件名用于本地命名
 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("爬取失败")

猜你喜欢

转载自www.cnblogs.com/fcbyoung/p/12291235.html