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

 找回密码
 立即注册

蜘蛛合约

发布者: 笨鸟自学网



定制合同

如果您发现您需要比内置Scrapy契约更多的功能,那么可以使用 SPIDER_CONTRACTS 设置:

SPIDER_CONTRACTS = {
    'myproject.contracts.ResponseCheck': 10,
    'myproject.contracts.ItemValidate': 10,
}

每个合同必须继承自 Contract 可以覆盖三种方法:

classscrapy.contracts.Contract(method*args)[源代码]
参数
  • method (collections.abc.Callable) -- 与合同关联的回调函数

  • args (list) -- 传入docstring的参数列表(空格分隔)

adjust_request_args(args)[源代码]

这会收到一个 dict 作为包含请求对象的默认参数的参数。 Request 默认情况下使用,但可以使用 request_cls 属性。如果链中的多个合同定义了此属性,则使用最后一个。

必须返回相同或修改过的版本。

pre_process(response)

这允许在将样本请求传递到回调之前,对从该请求接收的响应进行各种检查。

post_process(output)

这允许处理回调的输出。迭代器在传递给这个钩子之前被转换为列表化的。

提高 ContractFail 从 pre_process 或 post_process 如果未达到预期:

classscrapy.exceptions.ContractFail[源代码]

合同失败时出现的错误

下面是一个演示合同,它检查收到的响应中是否存在自定义头:

from scrapy.contracts import Contract
from scrapy.exceptions import ContractFail

class HasHeaderContract(Contract):
    """ Demo contract which checks the presence of a custom header
        @has_header X-CustomHeader
    """

    name = 'has_header'

    def pre_process(self, response):
        for header in self.args:
            if header not in response.headers:
                raise ContractFail('X-CustomHeader not present')

正在检测检查运行

什么时候? scrapy check 正在运行, SCRAPY_CHECK 环境变量设置为 true 字符串。你可以用 os.environ 在以下情况下对蜘蛛或设置执行任何更改: scrapy check 用途:

import os
import scrapy

class ExampleSpider(scrapy.Spider):
    name = 'example'

    def __init__(self):
        if os.environ.get('SCRAPY_CHECK'):
            pass  # Do some scraper adjustments when a check is running
12
上一篇:调试spiders下一篇:常用做法

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

GMT+8, 2024-9-8 11:33 , Processed in 0.515837 second(s), 17 queries .

© 2001-2020

返回顶部