抑制Scrapy项目在管道后打印在日志中

din*_*ino 21 python scrapy

我有一个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)
Run Code Online (Sandbox Code Playgroud)

如果我可以避免,我宁愿不把所有这些数据都写入日志文件.有关如何抑制此输出的任何建议?

din*_*ino 21

另一种方法是覆盖子类的__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})
Run Code Online (Sandbox Code Playgroud)

这样,您可以保持日志级别DEBUG并仅显示要从管道中看到的属性(attr1例如,检查).

  • 为我工作,使用`return repr({"attr1":self ["attr1"]})` (5认同)
  • 对我来说,它应该是`return repr({'attr1':self['attr1']})` (2认同)

Tal*_*lin 11

通读了文档并对源代码进行了(简要)搜索,我看不到实现这一目标的直接方法.

锤子方法是将设置中的日志记录级别设置为INFO(即将以下行添加到settings.py):

LOG_LEVEL='INFO'

这将删除有关正在爬网的URL /页面的许多其他信息,但它肯定会禁止有关已处理项目的数据.


Kur*_*Rao 8

我试过repre通过@dino提到的方式,它不能很好地工作.但是从他的想法演变而来,我尝试了str方法,并且它有效.

这是我如何做到的,非常简单:

    def __str__(self):
        return ""
Run Code Online (Sandbox Code Playgroud)


mpe*_*rin 5

如果只想排除输出的某些属性,则可以扩展@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=(',', ': '))
Run Code Online (Sandbox Code Playgroud)


Mar*_*erd 5

如果您是因为多年后遇到同样的问题而找到了这里,那么最简单的方法是使用LogFormatter

class QuietLogFormatter(scrapy.logformatter.LogFormatter):
    def scraped(self, item, response, spider):
        return (
            super().scraped(item, response, spider)
            if spider.settings.getbool("LOG_SCRAPED_ITEMS")
            else None
        )
Run Code Online (Sandbox Code Playgroud)

只需添加LOG_FORMATTER = "path.to.QuietLogFormatter"到您的settings.py,您将看到DEBUG除已抓取项目之外的所有消息。随着LOG_SCRAPED_ITEMS = True您无需更改即可恢复以前的行为LOG_FORMATTER

同样,您可以自定义已爬网页面和已删除项目的日志记录行为。

编辑:我在这个库中包含了这个格式化程序和其他一些 Scrapy 的东西。