Bootstrap

python爬虫之scrapy图片数据爬取

python爬虫之scrapy图片数据爬取

图片数据爬取之ImagesPipeline:
1、基于scrapy爬取字符串类型的数据和爬取图片类型的数据区别?
字符型:只需要基于xpath进行解析且提交管道进行持久化存储
图片:xpath解析出图片src的属性值。单独的对图片地址发起请求获取图片二进制类型的数据
2、ImagesPipeline:
只需要将img的src的属性值进行解析,提交到管道,管道就会对图片的src进行请求发送获取图片的二进制类型的数据,且还会帮我们进行持久化存储。
3、需求:爬取站长素材中的高清图片
4、使用流程:
(1)数据解析(图片的地址)img.py

import scrapy
from imgsPro.items import ImgsproItem

class ImgSpider(scrapy.Spider):
    name = "img"
    # allowed_domains = ["www.xxx.com"]
    start_urls = ["https://sc.chinaz.com/tupian/"]

    def parse(self, response):
        div_list = response.xpath('//div[@class="container"]/div[2]/div')
        # print(div_list)
        for div in div_list:
            #注意伪属性(图片懒加载)
            src = "https:" + str(div.xpath('./img/@data-original').extract_first())

            item = ImgsproItem()
            item['src'] = src

            yield item


(2)将存储图片地址的item提交到指定的管道类 items.py

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy


class ImgsproItem(scrapy.Item):
    # define the fields for your item here like:
    src = scrapy.Field()
    pass

(3)在管道文件中自定制一个基于ImagesPipeLine的一个管道类 pipelines.py
1)get_media_request
2)file_path
3)item_completed

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


# class ImgsproPipeline:
#     def process_item(self, item, spider):
#         return item
from scrapy.pipelines.images import ImagesPipeline
import scrapy
class imagesPipeline(ImagesPipeline):

    #就是可以根据图片地址进行图片数据的请求
    def get_media_requests(self, item, info):

        yield scrapy.Request(item['src'])

    #指定图片存储的路径
    def file_path(self, request, response=None, info=None, *, item=None):
        imgName = request.url.split('/')[-1]
        return imgName

    def item_completed(self, results, item, info):
        return item #返回给下一个即将被执行的管道类

(4)在配置文件中:
指定图片存储的目录:IMAGES_STORE = ‘./imgs’
指定开启的管道:自定制的管道类

全部代码资源如下:

;