scrapy -- 图片数据爬取之ImagesPipeline

基于图片数据的爬取,可以用框架中封装好的类,去进行图片的爬取,已经数据持久化存储

基于 站长素材 网站,进行数据的爬取

因为该网站会涉及到一个图片懒加载的反爬机制

代码示例:

#1.爬虫文件.py代码示例:

import scrapy
from imgsPro.items import ImgsproItem

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

    def parse(self, response):
        div_list = response.xpath('//div[@id="container"]/div')
        for div in div_list:
            #注意:使用伪属性
            src = div.xpath('./div/a/img/@src2').extract_first()

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

            yield item

# 2.items.py文件代码示例:

import scrapy


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

#3.pipeline.py文件代码示例:


from scrapy.pipelines.images import ImagesPipeline  #导入ImagesPipeline类
 
import scrapy
class imgsPileLine(ImagesPipeline): #新类继承ImagesPipeline类

    #就是可以根据图片地址进行图片数据的请求,重写父类的方法
    def get_media_requests(self, item, info):
        #手动向管道itme中的url发送请求
        yield scrapy.Request(item['src'])

    #指定图片存储的路径
    def file_path(self, request, response=None, info=None):
        #根据URL来生成图片的名称
        imgName = request.url.split('/')[-1]
        return imgName

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

#settings.py文件中,配置一个图片存储的路径,例如:
IMAGES_STORE = './imgs_file'

用法总结:

- 图片数据爬取之ImagesPipeline
    - 基于scrapy爬取字符串类型的数据和爬取图片类型的数据区别?
        - 字符串:只需要基于xpath进行解析且提交管道进行持久化存储
        - 图片:xpath解析出图片src的属性值。单独的对图片地址发起请求获取图片二进制类型的数据

    - ImagesPipeline:
        - 只需要将img的src的属性值进行解析,提交到管道,管道就会对图片的src进行请求发送获取图片的二进制类型的数据,且还会帮我们进行持久化存储。
    - 需求:爬取站长素材中的高清图片
    - 使用流程:
        - 数据解析(图片的地址)
        - 将存储图片地址的item提交到制定的管道类
        - 在管道文件中自定制一个基于ImagesPipeLine的一个管道类
            - get_media_request
            - file_path
            - item_completed
        - 在配置文件中:
            - 指定图片存储的目录:IMAGES_STORE = './imgs_bobo'
            - 指定开启的管道:自定制的管道类
posted @ 2022-04-27 23:37  志强爱璇璇  阅读(299)  评论(0)    收藏  举报