网络爬虫之爬取网络图片并保存

匿名 (未验证) 提交于 2019-12-03 00:18:01

将网页上的图片爬取之后,以图片原有名字保存在本地
代码:

import requests import os url="http://p1.so.qhmsg.com/bdr/_240_/t01dab8b2e73fe661d6.jpg" root="D://pics//"   #根目录 path=root+url.split('/')[-1] #根目录加上url中以反斜杠分割的最后一部分,即可以以图片原来的名字存储在本地 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("爬取失败")

运行结果:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!