2016-09-15 29 views
1

我無法找到該問題的答案。我如何能scrapy蜘蛛退出後執行Python代碼:Python Scrapy - 蜘蛛退出後執行代碼

我做這解析響應函數內部的以下(DEF parse_item(個體經營,響應):): self.my_function() 比我定義創建my_function (),但問題在於它仍然在蜘蛛的循環中。我的主要想法是使用收集的數據在蜘蛛循環之外的函數中執行給定的代碼。 謝謝。

回答

3

使用Scrapy類的功能closed如下:

class MySpider(scrapy.Spider): 
    # some attributes 
    spider_attr=[] 

    def parse(self, response): 
     # do your logic here 
     # page_text = response.xpath('//text()').extract() 
     self.spider_attr.append(whatever) 

    def closed(self, reason): 
     # will be called when the crawler process ends 
     # any code 
     # do something with collected data 
     for i in self.spider_attr: 
      print i 
+0

有沒有提供所收集的數據,以該功能(「關閉」)的方法嗎? –

+0

您可以將屬性添加到MySpider類。然後通過'self.attributename'訪問方法closed()中的屬性 – Kruser