首页 > 技术文章 > python requests库爬取网页小实例:爬取网页图片

wyhluckdog 2019-04-23 21:37 原文

爬取网页图片:

#网络图片爬取
import requests
import os
root="C://Users//Lenovo//Desktop//"
#以原文件名作为保存的文件名
path=root+url.split("/")[-1]
url="http://placekitten.com/g/500/600"
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("爬取失败")
r=requests.get(url)

 

推荐阅读