python-3.x - 根据蜘蛛属性更新scrapy设置

标签 python-3.x scrapy

有没有办法用scrapy来动态在运行时给出的蜘蛛设置?
我想添加一个 isDebug变量给我的蜘蛛,根据它的值,我想调整日志级别、管道和各种其他设置......

当尝试按照手册中的说明操作设置时,如下所示:

    def from_crawler(cls, crawler):
        settings = crawler.settings
        settings['USER_AGENT'] = 'Overwridden-UA'

我总是收到 TypeError: Trying to modify an immutable Settings object

最佳答案

Settings object 本身是不可变的,但有许多 set 方法,例如 settings.set https://github.com/scrapy/scrapy/blob/129421c7e31b89b9b0f9c5f7d8ae59e47df36091/scrapy/settings/init.py#L234

最新版本的 Scrapy(从 1.0 开始)蜘蛛有类方法 update_settings

@classmethod
def update_settings(cls, settings):
    settings.setdict(cls.custom_settings or {}, priority='spider')

这旨在用 custom_settings 中提供的设置覆盖设置蜘蛛的属性。因此,为了达到您的目标,您可以以某种方式覆盖该方法
class TheSpider(scrapy.Spider):
    name = 'thespider'
    is_debug = True
    custom_debug_settings = {
       # Put your debug settings here
    }

    @classmethod
    def update_settings(cls, settings):
        settings.setdict(getattr(cls, 'custom_debug_settings' \
                                      if getattr(cls, 'is_debug', False) \
                                      else 'custom_settings', None) or {},
                         priority='spider')

当然,项目范围内的“两勺 Django”方式可以用于调试目的的自定义设置文件,因此它可能是这样的:

设置.py (添加到文件末尾):
try:
    from dev_settings import *
except ImportError:
    pass

然后你可以创建 dev_settings.py 在 settings.py 旁边添加您想要为开发目的自定义的设置 - 如果 ,它们将被覆盖dev_settings.py 如果不存在,则存在或导入将被忽略。

关于python-3.x - 根据蜘蛛属性更新scrapy设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42134570/

相关文章:

python - python套接字模块中未定义的名称错误

javascript - hrefs的空列表通过JavaScript onclick函数实现分页

python - 具有相似模式的多个 if 语句

python - 集成 Django Rest Framework 和 Scrapy

python - 为什么我会收到 discord.py AttributeError : 'str' object has no attribute 'trigger_typing'

python - 为什么 'tornado.ioloop.IOLoop.instance().start()' 给我一个错误?

正则表达式检查字符串中是否不存在字符

python - Python 中带键的 sort_values()

python - Scrapy::如何获取导出到 .csv 的异常请求?

python - Scrapy 导入错误 : cannot import name 'HTTPClientFactory' from 'twisted.web.client' (unknown location)