Exceptions
Built-in Exceptions reference
这是scrapy包含的例外和他们的用法
CloseSpider
exception scrapy.exceptions.CloseSpider(reason='cancelled')
这个例外可以在爬虫的回调函数关闭/停止请求爬虫时生成。
参数:
reason(str)-关闭的原因
For example:
def parse_page(self, response):
if 'Bandwidth exceeded' in response.body:
raise CloseSpider('bandwidth_exceeded')
DontCloseSpider
- exception
scrapy.exceptions.``DontCloseSpider
[source]
这个例外可以生成在spider_idle信号处理器中来阻止爬虫被关闭
DropItem
- exception
scrapy.exceptions.``DropItem
[source]
这个例外必须在item pipline阶段生成来停止处理某个item。For more information see Item Pipeline.
IgnoreRequest
- exception
scrapy.exceptions.``IgnoreRequest
[source]
这个例外可以由调度器和任何下载器中间件生成,来表示那个请求应该忽略
NotConfigured
- exception
scrapy.exceptions.``NotConfigured
[source]
这个例外可以由一些组件生成,来表示他们会保持禁用。这些组件有
- Extensions
- Item pipelines
- Downloader middlewares
- Spider middlewares
这个例外必须在组件的__init__ 方法里生成。
NotSupported
- exception
scrapy.exceptions.``NotSupported
[source]
这个例外被生成来表示一个不支持的特征。
StopDownload
New in version 2.2.
- exception
scrapy.exceptions.``StopDownload
(fail=True)[source]
bytes_received信号处理器生成来表示对这个响应没有更多的自己要下载了。
fail这个布尔值参数控制处理响应结果的方法。
- If
fail=True
(default), 如果为True,请求的errback就会调用。响应对象就像stopdownload例外的response属性可用,这个会作为接收的Failure对象的value 的属性依次保存。也就是说,在def errback(self, failure)中,响应可以通过failure.value.response来访问。 - If
fail=False
, 如果时False, 就调用请求的回调函数。
所有情况下,响应体会被截断,body会包含所有接收的字节直到例外生成,包括信号处理器用来生成例外的字节。另外,响应对象会在Response.flags属性中标记download_stopped。
Note
fail只是一个关键字参数,即生成StopDownload(False)
or StopDownload(True)
will raise a TypeError
.
See the documentation for the bytes_received
signal and the Stopping the download of a Response topic for additional information and examples.
Logging
Note
scrapy.log 和它的功能已经不推荐了,推荐显示的调用python标准日志,继续阅读来获得更多日志系统的信息。
scrapy 使用logging 信息时间日志记录。我们会提供一些简单的例子来入门,但是更多高级用法例子强烈建议去仔细阅读它的文档。
日志功能开箱即用,可用使用scrapy 设置列出的 Logging settings来进行一些程度的配置。
scrapy调用scrapy.utils.log.configure_logging()
来设置一些合理的默认值和在运行命令时处理一些 Logging settings的设置。所有,建议手动调用如果你要从脚本中运行scrapy。described in Run Scrapy from a script.
Log levels
python内置的日志定义了五个不同的级别用来表明所给日志消息的严重程度。递减排序。
logging.CRITICAL
- 严重错误(最高)logging.ERROR
- 通常的错误logging.WARNING
- 警告消息logging.INFO
- 信息性的消息logging.DEBUG
- f 调试的消息。(最低)
How to log messages
这个例子展示了使用logging.WARNING来记录消息。
import logging
logging.warning("This is a warning")
这是发行日志消息以这五种标准级别的简写,也有通用的logging.log方法接收一个级别作为参数,如果需要,例如上面那个例子也可以这样写。
import logging
logging.log(logging.WARNING, "This is a warning")
最重要的是,你可以创建不同的记录器来封装消息。(例如,一个常见的尝试是给每个模块创建不同的记录器。)这些记录区可以独立配置,并且允许等级制结构。
前面的例子在后台使用root记录区,这是最顶级的记录器所有的消息都会被传播(除非那些指定的)。使用logging帮助程序只是显示的获得root记录器的简写,所有这也等同于后面这个片段。
import logging
logger = logging.getLogger()
logger.warning("This is a warning")
你可以使用不同记录器,只要把名字给logging.getlogger 函数就行。
import logging
logger = logging.getLogger('mycustomlogger')
logger.warning("This is a warning")
最后,如果你工作的地方有对任意模块的自定义记录器,你可以使用__name__ 变量,这会填充当前模块的路径。
import logging
logger = logging.getLogger(__name__)
logger.warning("This is a warning")
See also
Logging from Spiders
scrapy 的每个爬虫示例都提供了一个logger,这可以访问和使用像下面
import scrapy
class MySpider(scrapy.Spider):
name = 'myspider'
start_urls = ['https://scrapinghub.com']
def parse(self, response):
self.logger.info('Parse function called on %s', response.url)
记录器使用爬虫名来创建,但是你可以使用任何自定义的python记录器,例如:
import logging
import scrapy
logger = logging.getLogger('mycustomlogger')
class MySpider(scrapy.Spider):
name = 'myspider'
start_urls = ['https://scrapinghub.com']
def parse(self, response):
logger.info('Parse function called on %s', response.url)
Logging configuration
记录器自己不会管理通过他们展示的消息,为了这个任务,不同的处理器可以依附于任何记录器示例,然后他们可以重定向这些消息到正确的目的地,例如,标准输出,文件,Emails,等。
默认,scrapy 为root记录器设置和配置处理器,以下面的设置为基础:
Logging settings
These settings can be used to configure the logging:
第一组设置定义了日志消息的目的地,如果LOG_FILE被设置,通过root记录器发送的消息会重定向到使用LOG_ENCODING编码的LOG_FILE定义的文件名。如果没有设置和LOG_ENABLED是True,日志消息会在标准错误中展示。最后,如果LOG_ENABLED是False,就不会输出任何可见的日志。
LOG_LEVEL定义了展示的最小等级,更低的消息会被过滤。范围就是那五个等级。
LOG——FORMAT and LOG_DATEFORMAT 指定了所有消息版面使用的格式化字符串。这些设置可以包含任何列举在logging’s logrecord attributes docs and datetime’s strftime and strptime directives 的占位符。
如果LOG_SHORT_NAME被设置了,那么日志就不会展示打印日志的组件,默认是不设置的,因此日志包含复制输出日志的组件。
Command-line options
这是命令行的参数,可用于所有命令,你可以用来覆盖赛一些scrapy的日志设置。
-
–logfile FILE
Overrides
LOG_FILE
-
–loglevel/-L LEVEL
Overrides
LOG_LEVEL
-
–nolog
Sets
LOG_ENABLED
toFalse
See also
-
Module
logging.handlers
关于可用的处理器的进一步文档。
Custom Log Formats
通过扩展LogFormatter类并将LOG_FORMATTER指向你的新类,可用为不同的操作设置自定义的日志格式。
classscrapy.logformatter.``LogFormatter
[source]
为不同操作生成日志消息的类。
所有的方法必须返回有level msg and args参数的字典,在调用logging.log是要用来构建日志消息。
这些方法输出的键:
level
ilevel 是操作的日志顶级,你可以使用来自 python logging library :logging.DEBUG
,logging.INFO
,logging.WARNING
,logging.ERROR
andlogging.CRITICAL
.msg
应该是包含了不同格式化占位符的字符串。这个字符串,使用提供的args格式化,将称为这个操作的long message.args
应该是一个元组或字典包含msg的格式化占位符。最终日志消息以msg%args计算。
用户可以自己定义LogFormatter类,如果想自定义每个行为怎样记录或想完全的忽略。为了忽略一个行为,这个方法必须返回None。
这个例子展示怎样创造一个自定义的日志格式化程序来,来降低从管道删除item时日志的严重性级
class PoliteLogFormatter(logformatter.LogFormatter):
def dropped(self, item, exception, response, spider):
return {
'level': logging.INFO, # lowering the level from logging.WARNING
'msg': u"Dropped: %(exception)s" + os.linesep + "%(item)s",
'args': {
'exception': exception,
'item': item,
}
}
crawled
(request, response, spider)[source]
当发现一个网页时记录的消息。
download_error
(failure, request, spider, errmsg=None)[source]
从爬虫中记录下载错误的消息(特别是来自引擎的)。
dropped
(item, exception, response, spider)[source]
Logs a message when an item is dropped while it is passing through the item pipeline.# 当通过item pipline时一个item被丢弃而记录的消息。
item_error
(item, exception, response, spider)[source]
当通过item pipeline 时如果一个item造成一个错误,而记录的消息
scraped
(item, response, spider)[source]
当爬虫抓取了一个item时记录的消息
spider_error
(failure, request, response, spider)[source]
从爬虫中记录错误的消息。
Advanced customization
因为scrapy使用标准的logging模块,你可以使用所有标准logging的特性来定制日志
例如,你抓取的网站返回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 然后重新运行。
然后我们看到这个消息有INFO级别。为了隐藏这个应该设置scrapy.spidermiddlewares.httperror
位更高的级别;INFO的下个级别时WARNING,可以在spider的__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
的INFO消息就会被忽略。
scrapy.utils.log module
scrapy.utils.log.configure_logging(settings=None,install_root_handler=True)
scrapy的初始化的日志的默认值。
Parameters
- settings 字典,Settings对象或None,用来创造和配置root logger的处理器(默认None)
- install_root_handler (bool) – 是否下载root 日志处理器,默认True。
This function does:
- 通过python标准日志记录发送警告和twisted记录。
- 分别给scrapy 和 Twisted记录器分配DEBUG ERROR级别
- 如果LOG_STDOUT设置为True,发送标准输出给日志
当 install_root_handler
为True,这个函数还会根据所给的设置(see Logging settings)来为root记录器创建一个处理器。你可以使用settings参数来重写默认的选项。当settings时空或None,就用默认的。
但是在使用 CrawlerRunner
时需要精确的调用,这种情况下,这种用法不但需要而且是推荐的。
在运行自定义脚本时另一个选择时手动配置日志记录,为此可以使用logging.bassicConfig() 来设置一个基本的root处理器
注意 CrawlerProcess
自动的调用configure_logging, 所以只推荐use logging.basicConfig()
together with CrawlerRunner
。
这个例子展示了怎样重定向INFO 或更高的消息到一个文件。
import logging
logging.basicConfig(
filename='log.txt',
format='%(levelname)s: %(message)s',
level=logging.INFO
)
这种使用scrapy的方式参考Run Scrapy from a script 获得更多细节。