我目前在我正在构建的抓取工具的设置模块中设置了 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/