- 图片数据爬取之ImagesPipeline
- 基于scrapy爬取字符串类型的数据和爬取图片类型的数据的区别?
- 字符串:只需要基于xpath进行解析且提交管道进行持久化存储。
- 图片:xpath解析出图片src的属性值。单独的对图片地址发起请求获取图片二进制类型的数据
- xpath 提供了 imagespipeline 帮助我们处理图片的src,只需要将img的src的属性值进行解析,提交到管道,管道就会对图片的src属性值进行请求发送获取图片的二进制类型的数据,且还会帮助我们进行持久化存储
- 需求:爬取站长素材中的高清图片
- 使用流程:
- 数据解析(图片的地址)
- 将存储图片的item提交给指定的管道类
- 在管道文件中自定制一个基于ImagesPipeLine的一个管道类,需要重写三个方法:
- get_media_request()
- file_path()
- item_completed()
- 在配置文件中(settings):
- 指定图片存储的目录:IMAGES_STORE = ‘./imgs’
- 指定开启的管道:(基于自定制的管道类)
- 基于scrapy爬取字符串类型的数据和爬取图片类型的数据的区别?
setting.py
# -*- coding: utf-8 -*-
# Scrapy settings for imgsPro project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://doc.scrapy.org/en/latest/topics/settings.html
# https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
# https://doc.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'imgsPro'
SPIDER_MODULES = ['imgsPro.spiders']
NEWSPIDER_MODULE = 'imgsPro.spiders'
LOG_LEVEL = 'ERROR'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
# Obey robots.txt rules
ROBOTSTXT_OBEY = False
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
#