如果大家在使用scrapy时,调用过信号处理,如下面的实现方式
@classmethod
def from_crawler(cls, crawler, *args, **kwargs):
spider = cls()
crawler.signals.connect(spider.closeSpider, signals.spider_closed)
return spider
def closeSpider(self):
sys.stdout.flush()
self.imp_data.close_data()
MyCommon.warn_out("共有{}页,执行了{}页,取得产品{}个"
.format(self.pages, self.act_pages, self.get_goods_count))
那很有可能在后期处理时,会发生object has no attribute ‘crawler’
应该使用以下两种方式进行信号的传递
方法一:
@classmethod
def from_crawler(cls, crawler, *args, **kwargs):
# self = cls() 通过此方式生成的self,在后期处理时,可能会发生object has no attribute 'crawler'的错误
spider = super(GetimpgoodsSpider, cls).from_crawler(crawler, *args, **kwargs)
crawler.signals.connect(spider.closeSpider, signals.spider_closed)
return spider
def closeSpider(self):
sys.stdout.flush()
self.imp_data.close_data()
MyCommon.warn_out("共有{}页,执行了{}页,取得产品{}个"
.format(self.pages, self.act_pages, self.get_goods_count))
方法二:
1、引入from scrapy.xlib.pydispatch import dispatcher模块,这模块的引入将要不支持了,可以使用from pydispatch import dispatcher
2、在程序内部合适位置,一般是初始化方法中添加信号绑定处理
def __init__(self, name=None, **kwargs):
dispatcher.connect(self.closeSpider, signals.spider_closed)
self.imp_data = ImpData()
self.getGoods = GetGoods()
super().__init__(name, **kwargs)