好斗的。开始爬行后如何更改蜘蛛设置?

2024-04-22

我无法更改解析方法中的蜘蛛设置。但这绝对是一个办法。

例如:



class SomeSpider(BaseSpider):
    name = 'mySpider'
    allowed_domains = ['example.com']
    start_urls = ['http://example.com']
    settings.overrides['ITEM_PIPELINES'] = ['myproject.pipelines.FirstPipeline']
    print settings['ITEM_PIPELINES'][0]
    #printed 'myproject.pipelines.FirstPipeline'
    def parse(self, response):
        #...some code
        settings.overrides['ITEM_PIPELINES'] = ['myproject.pipelines.SecondPipeline']
        print settings['ITEM_PIPELINES'][0]
        # printed 'myproject.pipelines.SecondPipeline'
        item = Myitem()
        item['mame'] = 'Name for SecondPipeline'  
  

但!项目将由 FirstPipeline 处理。新的 ITEM_PIPELINES 参数不起作用。 开始抓取后如何更改设置?提前致谢!


如果您希望不同的蜘蛛具有不同的管道,您可以为蜘蛛设置管道列表属性,该属性定义该蜘蛛的管道。比在管道中检查是否存在:

class MyPipeline(object):

    def process_item(self, item, spider):
        if self.__class__.__name__ not in getattr(spider, 'pipelines',[]):
            return item
        ...
        return item

class MySpider(CrawlSpider):
    pipelines = set([
        'MyPipeline',
        'MyPipeline3',
    ])

如果您希望不同的项目由不同的管道处理,您可以这样做:

    class MyPipeline2(object):
        def process_item(self, item, spider):
            if isinstance(item, MyItem):
                ...
                return item
            return item
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

好斗的。开始爬行后如何更改蜘蛛设置? 的相关文章

随机推荐