[笔记]python网络爬虫:一个简单的爬取图片并存储示例

代码:

import requests
import os

url='https://pic1.zhimg.com/4f17c1deab55be53b5ba52dafe2f2938_r.jpg' 
#网站地址,这个图片来自于知乎的问题“自拍特别好看是什么感觉”
root='D:\project\Len_WebScrape\example_picture'
#存储的文件夹的地址
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('爬取图片失败')

运行结果:

文件保存成功

[笔记]python网络爬虫:一个简单的爬取图片并存储示例_第1张图片

该示例参考大学mooc课程《python网络爬虫和信息提取》
(http://www.icourse163.org/course/BIT-1001870001)

你可能感兴趣的:(爬虫,python)