python - Scrapy 如何从命令行参数设置 DEPTH_LIMIT

标签 python scrapy

我目前在我正在构建的抓取工具的设置模块中设置了 DEPTH_LIMIT。我希望能够将深度限制作为命令行参数传递。我尝试了以下作为爬虫(及其变体)的构造函数:

    def __init__(self, max_depth=3, *args, **kwargs):
        super(MySpider, self).__init__(*args, **kwargs)
        self.settings['DEPTH_LIMIT'] = int(max_depth)

但是,我得到一个错误,堆栈转储以:

结尾
  File "/usr/local/lib/python2.7/dist-packages/scrapy/spider.py", line 41, in crawler
      assert hasattr(self, '_crawler'), "Spider not bounded to any crawler"
   AssertionError: Spider not bounded to any crawler

即使尝试在构造函数中打印 self.settings['DEPTH_LIMIT'] 也会导致错误。如何通过命令行参数在爬虫中设置 DEPTH_LIMIT?

谢谢!

最佳答案

你可以试试这个方法:

def __init__(self, *args, **kwargs):
    self.settings['DEPTH_LIMIT'] = int(kwargs.pop('max_depth', 3))
    super(MySpider, self).__init__(*args, **kwargs)

关于pop的细节可以引用python official documentation

如果这不起作用,请添加更多关于如何创建爬虫对象的代码(例如类定义,以及在哪里定义 settings 属性)

关于python - Scrapy 如何从命令行参数设置 DEPTH_LIMIT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20828401/

相关文章:

Python 寻求读取不断增长的文件

python - Pygame 不会检测同一类中的列表

python - 带有三重引号的 Jupyter Notebook Python 自动文档字符串生成

python multiprocessing - 将子进程日志记录发送到在父进程中运行的 GUI

python - 为什么需要为 Python 设置环境变量才能使 Scrapy 工作?

python - Scrapy 新手问题 - 教程文件无法运行

python - 如何在 Python 中使用 x^2 进行(空中飞人)集成?

xpath - “<i>”中断正确的节点选择

scrapy - 覆盖 Scrapy 输出格式 'on the fly'

javascript - python scrapy - 从 onclick 弹出对话框中抓取