Python爬虫入门记(5)- 批量下载图片(正则表达式,以百度文库为例)

五、批量下载图片

1. 调用库函数

【通过链接下载图片有多种方法,本文采用其中一种】

from builtins import len, hasattr, range  # 提供对Python的“内置”标识符的直接访问
import re  # 正则表达式
import urllib.request, urllib.error  # 提供了一系列用于操作URL的功能
import requests  # Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库。与urllib相比,Requests更加方便,用来下载图片
import os  # os模块,里面包含了很多操作文件和目录的函数。

2. 定义主函数和正则表达式

主函数:

def main():
    url = "https://wenku.baidu.com/view/ab00294a2079168884868762caaedd3382c4b57c.html"  # 网页链接
    f = open('data.txt', encoding='utf-8')  # 打开txt文件,以utf-8编码解码,不然会出错
    urls = f.read()  # 读取文件
    num = 1
    os.makedirs('./test1/', exist_ok=True)  # 在目录下新建文件夹
    # 因为图片有两种结构,所以有两个正则表达式
    pic_1 = re.findall(findImg1, urls)  # 使用re库,正则匹配找到图片链接,返回一个列表
    pic_2 = re.findall(findImg2, urls)
    pic_1 = pic_1 + pic_2  # 链接两个列表
    print('找到图片,即将开始下载图片...')
    for each in pic_1:
        print('正在下载第' + str(num) + '张图片,图片地址:' + str(each))
        # 异常处理
        try:
            if each is not None:
                pic = requests.get(each, timeout=7)  # 向服务器发出请求,返回一个包含服务器资源的Response对象,包含从服务器返回的所有的相关资源。
            else:
                continue
        except BaseException:
            print('错误,当前图片无法下载')
            continue
        else:
            # 图片保存路径,同时为每一张图片命名
            string = './test1/' + str(num) + '.jpg'
            fp = open(string, 'wb')
            fp.write(pic.content)
            fp.close()
        num += 1

正则表达式:

findImg1 = re.compile(r'<img src="(.*?)" alt="">')
findImg2 = re.compile(r'img data-src="(.*?)"')

【有个坑目前还没有填上,用爬虫爬取网页源代码时,只有前三张图片的链接,而后面几十张的图片都没有链接,但是直接查看网页源代码时,却可以看到,所以是直接复制的源代码到 txt ,再打开 txt 文件获取的源代码,有能力之后将会填上】

3.运行结果

Python爬虫入门记(5)-  批量下载图片(正则表达式,以百度文库为例)
Python爬虫入门记(5)-  批量下载图片(正则表达式,以百度文库为例)

上一篇:Vue中的前后台交互


下一篇:数据采集