Python爬虫入门实例七之网络图片的爬取和存储

一、 爬取原页面

1.网站链接

本例采用国家地理中文网

网站链接:http://www.ngchina.com.cn/.

2.要保存的图片

在这里插入图片描述

二、编程思路

1.图片转换二进制

  对于存储图片,我们首先要将图片转换成二进制,具体方法如下,先引入os库。

import os

  再用content函数将图片转换为二进制

 with open(path,'wb') as f:
            f.write(r.content)
            f.close()

2.以原图片名称命名图片

path = root + url.split('/')[-1]

三、完整代码

import requests
import os

url = 'http://image.ngchina.com.cn/2020/0812/20200812011133978.jpg'
root = "E://pics//"
path = root + url.split('/')[-1]#spilt 返回⼀个由字符串内单词组成的/分割的列表中的最后一个(即:图片的名字)
try:
    kv = {
    
    'user-agent': 'Mozilla/5.0'}
    if not os.path.exists(root):
        os.mkdir(root)
    if not os.path.exists(path):
        r = requests.get(url,headers=kv)
        with open(path,'wb') as f:
            f.write(r.content)
            f.close()
            print("文件保存成功")
    else:
        print("文件保存成功")
except:
    print("爬取失败")
    

  本篇完,如有错误欢迎指出~

引用源自

中国大学MOOC Python网络爬虫与信息提取
https://www.icourse163.org/course/BIT-1001870001

猜你喜欢

转载自blog.csdn.net/weixin_44578172/article/details/109377336
今日推荐