爬取网页图片并保存在本地
将网页上的图片爬取之后,以图片原有名字保存在本地
代码:
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("爬取失败")
运行结果: