__init__() 添加统计信息时缺少 1 个必需的位置参数

__init__() missing 1 required positional argument when added stats

我正在尝试从 scrapy 统计数据中获取 start_time。

在 scrapy doc 他们说了类似的话。

https://docs.scrapy.org/en/latest/topics/stats.html

好的,所以,正如他们所做的那样,我在 init 捕获了统计信息,但我收到一个错误,就像我没有传递统计参数一样。我不希望它像争论一样。这是我的代码。

pipelines.py

class MongoDBPipeline(object):

    def __init__(self, stats):
        self.timeStarted = stats.get_value('start_time')

    def process_item(self, item, spider):
        valid = True
        for data in item:
            if not data:
                valid = False
                raise DropItem("Missing {0}!".format(data))
            if valid:
                item['createdAt'] = self.timeStarted

                self.collection.insert(dict(item))
                logging.info("Video cargado.")
            return item

我得到的错误正是:

TypeError: __init__() missing 1 required positional argument: 'stats'

不知道该怎么办。 谢谢!

你忘了

@classmethod
def from_crawler(cls, crawler):
    return cls(crawler.stats)

which 运行s __init__ with argument crawler.stats

请参阅您的 link Common Stats Collector uses and Write items to MongoDB.
中的示例 两者都有 class 方法 from_crawler().

scrapy 使用

创建管道
MongoDBPipeline.from_crawler(crawler)

和原始 from_crawler() 运行s __init__(self) 没有参数 - 所以你的新 __init__(self, stats) 不能得到 stats 并且它显示错误。但是如果你添加自己的from_crawler() which 运行s __init__(self, stats) with crawler.stats then __init__(self, stats) will get it.


编辑: 显示它的最小示例。

它工作正常,但如果你删除 from_crawler(),它就会报错。

您可以将所有代码复制到一个文件中,并且 运行 作为 python script.py 而无需使用 scrapy from_crawlerscrapy getspider 创建项目。

import scrapy

class MySpider(scrapy.Spider):

    name = 'myspider'

    start_urls = ['http://books.toscrape.com/'] #'http://quotes.toscrape.com']

    def parse(self, response):
        print('url:', response.url)


class MyPipeline(object):

    def __init__(self, stats):
        print('__init__ stats:', stats)
        self.stats = stats

    @classmethod
    def from_crawler(cls, crawler):
        print('from_crawler stats:', crawler.stats)
        return cls(crawler.stats)

# ---

from scrapy.crawler import CrawlerProcess

c = CrawlerProcess({
    'ITEM_PIPELINES': {'__main__.MyPipeline': 1}, # used Pipeline created in current file (needs __main___)
})
c.crawl(MySpider)
c.start()