2012-03-07 130 views
1

我在單個scrapy項目中有多個蜘蛛。將文本文件寫入管道

我想爲蜘蛛名稱和時間戳爲每個蜘蛛編寫一個單獨的輸出文本文件。

當我有一個單一的蜘蛛,我在__init方法創建的文件,但現在我想是這樣,的Upromise將產生兩個輸出文件,而另一個則只有一個。

class MallCrawlerPipeline(object): 

def spider_opened(self, spider): 
    self.aWriter = csv.writer(open('../%s_%s.txt' % (spider.name, datetime.now().strftime("%Y%m%d_%H%M%S")), 'wb'), 
     delimiter=',', quoting=csv.QUOTE_MINIMAL) 
    self.aWriter.writerow(['mall', 'store', 'bonus', 'per_action', 'more_than','up_to', 'deal_url', 'category']) 

    if 'upromise' in spider.name: 
     self.cWriter = csv.writer(
      open('../%s_coupons_%s.txt' % (spider.name, datetime.now().strftime("%Y%m%d_%H%M%S")), 'wb'), 
      delimiter=',', quoting=csv.QUOTE_MINIMAL) 
     self.cWriter.writerow(['mall', 'store', 'bonus', 'per_action', 'more_than','up_to', 'deal_url', 'category']) 

def process_item(self, item, spider): 
    self.aWriter.writerow([item['mall'], item['store'], item['bonus'], item['per_action'], 
          item['more_than'], item['up_to'], item['deal_url'], item['category']]) 

    return item 

但我面對這個錯誤:

File "C:\Users\akhter\Dropbox\akhter\mall_crawler\mall_crawler\pipelines.py", line 24, in process_item 
    self.aWriter.writerow([item['mall'], item['store'], item['bonus'], item['per_action'], 
exceptions.AttributeError: 'MallCrawlerPipeline' object has no attribute 'aWriter' 

任何幫助,將不勝感激。提前致謝。

+1

哪裏定義了aWriter?這個對象是否應該從'object'以外的東西繼承? – 2012-03-07 20:42:31

+0

@ sr2222感謝您的回覆,但是,我非常抱歉,我沒有太多的Python蟒蛇,請你給我一個詳細的答案。 – 2012-03-08 07:00:55

回答

0

感謝球員我發現了一個答案,我只需要給一個信號,否則spider_opened永遠不會像這樣調用init方法。仍然歡迎提供建議

def __init__(self): 
    dispatcher.connect(self.spider_opened, signals.spider_opened) 
1

您確定您始終在obj.process_item(...)之前運行obj.spider_opened(...)?看起來你不是,就像在第一個方法調用之後那個屬性應該被添加到對象中一樣。

順便說一句,如果總是需要第一個方法調用,將它移動到__init__或從那裏調用它是有意義的。

+0

感謝您的回覆@Eduardo lvanec,如果我將其移至__init__,我如何訪問那裏的蜘蛛名稱? – 2012-03-08 07:02:36