概scrapy既然是一款强大的爬虫框架,自然也实现了图片和文件的下载,FilesPipeline、ImagesPipeline分别是图片和文件的下载器,image也是文件的一种为什么还要单独提供一个image下载器?这是因为图片下载器还提供了一些额外方法:缩略图生成、图片过滤;今天就来介绍这两款特殊的下载器。
使用方法
1.常规的使用方法是首先在item中定义关键字,images和files关键字段如下:
image
当然其中字段还可以增加可以加title、Word等自定义字段
2.在setting.py中启用下载管道
ITEM_PIPELINES = { 'scrapy.pipelines.files.FilesPipeline': 1, 'scrapy.pipelines.images.ImagesPipeline': 2}
上面启用的是内部的下载器,如果实现了自定义需要将路径替换为自定义的下载器
3.在爬虫主程序中传递url,yield item{'file_urls':[url1, url2,`````````]}
下面将从源码和案例来分析具体如何使用
注:file下载和image下载的原理是一样的,只是images下载图片可以配置,所以我们分析file的源码,讲image的实例
FilesPipeline源码
FilesPipeline文件位于:
scrapy.pipelines.files
源码有点多,我们只需要关注两个地方,一个是下载的实现一个是下载的文件命名
class FilesPipeline(MediaPipeline):
"""Abstract pipeline that implement the file downloading
This pipeline tries to minimize network transfers and file processing,
doing stat of the files and determining if file is new, uptodate or
expired.
`new` files are those that pipeline never processed and needs to be
downloaded from supplier site the first time.
`upt