这里使用scrapy内置的ImagePipeline来帮助我们下载图片。
详情参考:https://doc.scrapy.org/en/latest/topics/media-pipeline.html
一、 使用ImagePipeline的前提:
文档中有这么一句话 “The Images Pipeline uses Pillow for thumbnailing and normalizing images toJPEG/RGB format, so you need to install this library in order to use it.”也就是说要使用 ImagePipeline 就要先下载Pillow模块。
1,打开 https://pillow.readthedocs.io/en/latest/installation.html ,看一下warning内容,看一下自身是否存在不能正确安装的因素。
2,这里假设能正确安装,Windows下使用
pip install Pillow
来安装。
二、简单demo:
下载百度首页的logo
新建一个项目:
scrapy startproject Scrapy_ImagesPipeline
打开项目在spiders下建立一个spider_baidu.py的文件
import scrapyfrom Scrapy_ImagesPipeline.items import ScrapyImagespipelineItemclass SpiderBaidu( scrapy. Spider):name = "baidu"start_urls = [ 'https://www.baidu.com/']def parse( self, response):item = ScrapyImagespipelineItem()#这里偷懒,直接传入图片的链接了。item[ 'image_urls'] = [ 'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png']return item
items.py:
import scrapy
class
ScrapyImagespipelineItem(
scrapy.
Item):
# define the fields for your item here like:
image_urls = scrapy.Field()
#把路径放在这里,交给ImagePipeline处理
images = scrapy.Field()
#ImagePipeline负责往这里填充结果。
settings.py
加上两个很重要的参数:
#使用内置的ImagesPipelineITEM_PIPELINES = {'scrapy.pipelines.images.ImagesPipeline': 1,}#存储路径,存在当前目录下download_cacheIMAGES_STORE = './download_cache'
还可以在settings.py里加上一些配置,辅助下载,详情看文档,
例如:
缩略图:
IMAGES_THUMBS = { 'small': (50, 50), 'big': (270, 270), }
过滤图片大小:IMAGES_MIN_HEIGHT = 110 IMAGES_MIN_WIDTH = 110
三、运行程序,可以看到log有
{'image_urls': ['https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png'],
'images': [{'checksum': '2c946538602cbe08ccbc397e6cfbece1',
'path': 'full/17b1ff847e4a76c36d5cf84352a5a78273b8334d.jpg',
'url': 'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png'}]}
在当前目录下可以看到有download_cache文件下有一个full,存有图片,名称是 一长串字符串(URL的SHA1 hash )。
四、简单分析一下程序
把图片的链接给item['image_urls'],由内置的ImagePipeline处理。ImagePipeline处理后的结果填入item['images']中