2013-01-18 45 views
14

我有一個scrapy項目,最終進入我的管道的項目相對較大,並存儲大量的元數據和內容。一切都在我的蜘蛛和管道中正常工作。禁止Scrapy項目在管道後打印在日誌中

2013-01-17 18:42:17-0600 [tutorial] DEBUG: processing Pipeline pipeline module 
2013-01-17 18:42:17-0600 [tutorial] DEBUG: Scraped from <200 http://www.example.com> 
    {'attr1': 'value1', 
    'attr2': 'value2', 
    'attr3': 'value3', 
    ... 
    snip 
    ... 
    'attrN': 'valueN'} 
2013-01-17 18:42:18-0600 [tutorial] INFO: Closing spider (finished) 

我寧可不要這些數據吐到日誌文件,如果我能避免它:日誌,然而,當它離開管道(我相信)打印出整個scrapy項目。有關如何抑制此輸出的任何建議?

回答

13

另一種方法是重寫的__repr__方法Item子類有選擇地選擇在管線末端打印哪些屬性(如果有的話):

from scrapy.item import Item, Field 
class MyItem(Item): 
    attr1 = Field() 
    attr2 = Field() 
    # ... 
    attrN = Field() 

    def __repr__(self): 
     """only print out attr1 after exiting the Pipeline""" 
     return repr({"attr1": self.attr1}) 

這樣,您可以將日誌級別保留在DEBUG,並只顯示您想要看到的流水線屬性(例如,檢查attr1)。

+3

爲我工作給出了答案,使用'return repr({「attr1」:self [「attr1」]})' –

+0

對我來說,它應該是'return repr({'attr1':self ['attr1']})' –

7

通過閱讀文檔並通過源代碼進行(簡短)搜索,我無法看到實現此目標的簡單方法。

錘的方法是設置在設置於INFO日誌級別(即添加下列行來的settings.py):

LOG_LEVEL='INFO'

這將去掉了很多關於其它信息正在抓取的網址/網頁,但它肯定會壓制有關已處理項目的數據。

1

或者如果你知道蜘蛛正常工作,那麼你可以禁用整個記錄

LOG_ENABLED = False

我禁用,當我的履帶運行良好

6

我試過@dino提到的方式,它不能正常工作。但是從他的想法演變而來,我嘗試了這種方法,並且它可以工作。

這裏是我如何做到這一點,很簡單:

def __str__(self): 
     return "" 
+0

它適用於我, 謝謝 – ningyuwhut

2

如果要排除只輸出的某些屬性,可以延長通過@dino

from scrapy.item import Item, Field 
import json 

class MyItem(Item): 
    attr1 = Field() 
    attr2 = Field() 
    attr1ToExclude = Field() 
    attr2ToExclude = Field() 
    # ... 
    attrN = Field() 

    def __repr__(self): 
     r = {} 
     for attr, value in self.__dict__['_values'].iteritems(): 
      if attr not in ['attr1ToExclude', 'attr2ToExclude']: 
       r[attr] = value 
     return json.dumps(r, sort_keys=True, indent=4, separators=(',', ': '))