Scrapy自定义ImagePipeline Settings.py

时间:2015-05-15 21:20:45

标签: python scrapy

我已经为我的scrapy项目编写了自己的ImagePipeline。从我的谷歌搜索我得到有关如何在settings.py中设置pipline的不同信息。

我们说管道是MyImagesPipeline,它存在于pipelines.py中,其中包含:

class MyImagesPipeline(ImagesPipeline):
    def get_media_requests(self, item, info):
        for image_url in item['image_urls']:
            yield scrapy.Request(image_url)

    def item_completed(self, results, item, info):

        some processing...
        return item

在我的settings.py中:

ITEM_PIPELINES = {
    'scrapy.contrib.pipeline.images.ImagesPipeline': 1,
    'myproject.pipelines.MyImagesPipeline': 100,
   }

我有两个管道,因为如果我单独放入MyImagesPipeline,则调用item_completed但没有任何图像,我得到一个KeyError,因为字段'图像'不在这里。但是,如果设置中的两个中间件,我将获得同一图像的多个副本。

有人可以赐教我吗?

编辑:

蜘蛛代码很长,因为我在其中进行了大量的信息处理,但我认为这可能是相关部分(解析的回调):

def parse_data(self, response):
    img_urls = response.css('.product-image').xpath('.//img/@src').extract()
    img_url = img_urls[0]
    item['image_urls'] = [img_url,]
    yield item

1 个答案:

答案 0 :(得分:1)

两个图片管道都在处理您商品中的images_urls字段,这就是您将图片重复两次的原因。

我会尝试坚持使用单个管道并修复您遇到的任何错误,以获得处理整个图像处理的自包含组件。特别是,您必须更好地处理来自ImagesPipeline的继承。

关于KeyError,ImagesPipeline.item_completed方法is in charge of updating the images field in the items,如果您覆盖它,则在您需要时它将无法使用。

要在您的管道中修复它,您可以像这样更新它:

class MyImagesPipeline(ImagesPipeline):
    ...

    def item_completed(self, results, item, info):
        item = super(MyImagesPipeline, self).item_completed(results, item, info)

        some processing...
        return item

我建议检查ImagesPipeline的代码(它放在Scrapy 1.0中的scrapy/pipelines/images.py或以前版本中的scrapy/contrib/pipeline/images.py但代码几乎相同)以完全了解内部发生了什么它