笨鸟编程-零基础入门Pyhton教程

 找回密码
 立即注册

登录

发布者: 笨鸟自学网



高级自定义

因为scrapy使用stdlib日志记录模块,所以可以使用stdlib日志记录的所有功能自定义日志记录。

例如,假设您正在抓取一个返回许多HTTP 404和500响应的网站,并且您希望隐藏像这样的所有消息:

2016-12-16 22:00:06 [scrapy.spidermiddlewares.httperror] INFO: Ignoring
response <500 http://quotes.toscrape.com/page/1-34/>: HTTP status code
is not handled or not allowed

首先要注意的是一个记录器名称-它在括号中: [scrapy.spidermiddlewares.httperror] . 如果你得到公正 [scrapy] 然后 LOG_SHORT_NAMES 可能设置为true;设置为false并重新运行爬网。

接下来,我们可以看到消息具有信息级别。为了隐藏它,我们应该为 scrapy.spidermiddlewares.httperror 高于信息;信息后的下一级是警告。可以这样做,例如在蜘蛛的 __init__ 方法:

import logging
import scrapy


class MySpider(scrapy.Spider):
    # ...
    def __init__(self, *args, **kwargs):
        logger = logging.getLogger('scrapy.spidermiddlewares.httperror')
        logger.setLevel(logging.WARNING)
        super().__init__(*args, **kwargs)

如果您再次运行此蜘蛛,则从 scrapy.spidermiddlewares.httperror 日志记录器将消失。

您也可以通过以下方式来过滤日志记录 LogRecord 数据。例如,您可以使用子串或正则表达式按消息内容进行过滤日志记录。创建 logging.Filter 子类并为其配备正则表达式模式,以便过滤发出不需要的消息::

import logging
import re

class ContentFilter(logging.Filter):
    def filter(self, record):
        match = re.search(r'\d{3} [Ee]rror, retrying', record.message)
        if match:
            return False

项目级别的过滤可以附加到由Scrapy创建的根处理程序,这是对项目不同部分(中间件、蜘蛛等)的所有记录器进行过滤的一种便捷方式::

import logging
import scrapy

class MySpider(scrapy.Spider):
    # ...
    def __init__(self, *args, **kwargs):
        for handler in logging.root.handlers:
            handler.addFilter(ContentFilter())

或者,您也可以选择特定的记录器并将其隐藏,而不会影响其他记录器:

import logging
import scrapy

class MySpider(scrapy.Spider):
    # ...
    def __init__(self, *args, **kwargs):
        logger = logging.getLogger('my_logger')
        logger.addFilter(ContentFilter())
1234
上一篇:例外情况下一篇:统计数据集合

Archiver|手机版|笨鸟自学网 ( 粤ICP备20019910号 )

GMT+8, 2024-10-26 05:31 , Processed in 0.156729 second(s), 17 queries .

© 2001-2020

返回顶部