有没有方法为每只蜘蛛使用单独的scrapy管道?

uub*_*all 4 python scrapy web-scraping scrapy-spider

我想在不同的域下获取网页,这意味着我必须在命令"scrapy crawl myspider"下使用不同的蜘蛛.但是,由于网页内容不同,我必须使用不同的管道逻辑将数据放入数据库.但对于每个蜘蛛,它们必须遍历settings.py中定义的所有管道.是否有其他优雅的方法为每个蜘蛛使用单独的管道?

ale*_*cxe 9

ITEM_PIPELINES在引擎启动期间,为项目中的所有蜘蛛全局定义设置.它不能在飞行中每个蜘蛛改变.

以下是一些需要考虑的选项:

  • 更改管道代码.跳过/继续处理由process_item管道方法中的蜘蛛返回的项目,例如:

    def process_item(self, item, spider): 
        if spider.name not in ['spider1', 'spider2']: 
            return item  
    
        # process item
    
    Run Code Online (Sandbox Code Playgroud)
  • 更改开始抓取的方式.做到这一点从脚本的基础上,作为参数传递蜘蛛名,覆盖您ITEM_PIPELINES之前调用设置crawler.configure().

也可以看看:

希望有所帮助.


Tom*_*mmy 5

上面稍微好一点的版本如下.它更好,因为这种方式允许您比上面管道中的'not in ['spider1','spider2']'编码更容易选择性地为不同的蜘蛛开启管道.

在你的蜘蛛类中,添加:

#start_urls=...
pipelines = ['pipeline1', 'pipeline2'] #allows you to selectively turn on pipelines within spiders
#...
Run Code Online (Sandbox Code Playgroud)

然后在每个管道中,您可以将该getattr方法用作魔术.加:

class pipeline1():  
    def process_item(self, item, spider):
       if 'pipeline1' not in getattr(spider, 'pipelines'):
          return item
       #...keep going as normal  
Run Code Online (Sandbox Code Playgroud)