1.自定义pipeline
#一:可以写多个Pipeline类 #1、如果优先级高的Pipeline的process_item返回一个值或者None,会自动传给下一个pipline的process_item, #2、如果只想让第一个Pipeline执行,那得让第一个pipline的process_item抛出异常raise DropItem() #3、可以用spider.name == '爬虫名' 来控制哪些爬虫用哪些pipeline 二:示范 from scrapy.exceptions import DropItem class CustomPipeline(object): def __init__(self,v): self.value = v @classmethod def from_crawler(cls, crawler): """ Scrapy会先通过getattr判断我们是否自定义了from_crawler,有则调它来完 成实例化 """ val = crawler.settings.getint('MMMM') return cls(val) def open_spider(self,spider): """ 爬虫刚启动时执行一次 """ print('000000') def close_spider(self,spider): """ 爬虫关闭时执行一次 """ print('111111') def process_item(self, item, spider): # 操作并进行持久化 # return表示会被后续的pipeline继续处理 return item # 表示将item丢弃,不会被后续pipeline处理 # raise DropItem()
实例
#1、settings.py HOST="127.0.0.1" PORT=27017 USER="root" PWD="123" DB="amazon" TABLE="goods" ITEM_PIPELINES = { 'Amazon.pipelines.CustomPipeline': 200, } #2、pipelines.py class CustomPipeline(object): def __init__(self,host,port,user,pwd,db,table): self.host=host self.port=port self.user=user self.pwd=pwd self.db=db self.table=table @classmethod def from_crawler(cls, crawler): """ Scrapy会先通过getattr判断我们是否自定义了from_crawler,有则调它来完 成实例化 """ HOST = crawler.settings.get('HOST') PORT = crawler.settings.get('PORT') USER = crawler.settings.get('USER') PWD = crawler.settings.get('PWD') DB = crawler.settings.get('DB') TABLE = crawler.settings.get('TABLE') return cls(HOST,PORT,USER,PWD,DB,TABLE) def open_spider(self,spider): """ 爬虫刚启动时执行一次 """ self.client = MongoClient('mongodb://%s:%s@%s:%s' %(self.user,self.pwd,self.host,self.port)) def close_spider(self,spider): """ 爬虫关闭时执行一次 """ self.client.close() def process_item(self, item, spider): # 操作并进行持久化 self.client[self.db][self.table].save(dict(item))
2. 自定义扩展
自定义扩展(与django的信号类似) 1、django的信号是django是预留的扩展,信号一旦被触发,相应的功能就会执行 2、scrapy自定义扩展的好处是可以在任意我们想要的位置添加功能,而其他组件中提供的功能只能在规定的位置执行
#1、在与settings同级目录下新建一个文件,文件名可以为extentions.py,内容如下 from scrapy import signals class MyExtension(object): def __init__(self, value): self.value = value @classmethod def from_crawler(cls, crawler): val = crawler.settings.getint('MMMM') obj = cls(val) crawler.signals.connect(obj.spider_opened, signal=signals.spider_opened) crawler.signals.connect(obj.spider_closed, signal=signals.spider_closed) return obj def spider_opened(self, spider): print('=============>open') def spider_closed(self, spider): print('=============>close') #2、配置生效 EXTENSIONS = { "Amazon.extentions.MyExtension":200 }