【问题标题】:What triggers the from_crawler classmethod?什么触发了 from_crawler 类方法?
【发布时间】:2018-09-11 05:54:27
【问题描述】:

我正在使用 scrapy,并且我有以下功能管道类:

类 DynamicSQLlitePipeline(object):

@classmethod
def from_crawler(cls, crawler):
    # Here, you get whatever value was passed through the "table" parameter
    docket = getattr(crawler.spider, "docket")
    return cls(docket)

def __init__(self,docket):
    try:
        db_path = "sqlite:///"+settings.SETTINGS_PATH+"\\data.db"
        db = dataset.connect(db_path)
        table_name = docket[0:3]  # FIRST 3 LETTERS
        self.my_table = db[table_name]


    except Exception:
        # traceback.exec_print()
        pass

def process_item(self, item, spider):

    try:
        test = dict(item)
        self.my_table.insert(test)
        print('INSERTED')
    except IntegrityError:
            print('THIS IS A DUP')

在我的蜘蛛中,我有:

custom_settings = {
    'ITEM_PIPELINES': {

        'myproject.pipelines.DynamicSQLlitePipeline': 600,
    }
}

从最近的一个问题中,我被指向What is the 'cls' variable used for in Python classes?

如果我理解正确以便实例化管道对象(使用 init 函数),它需要一个案卷编号。只有在运行 from_crawler 类方法后,案卷编号才可用。但是是什么触发了 from_crawler 方法。代码再次运行。

【问题讨论】:

  • new_pipeline = DynamicSQLlitePipeline.from_crawler(crawler)
  • 您没有向我们展示的其他一些代码正在调用它,方法是执行DynamicSQLlitePipeline.from_crawler(crawler) 之类的操作。或者,也许,您将名称 DynamicSQLlitePipeline 传递给爬虫,它将其存储为 pipeline_type,然后调用 pipeline_type.from_crawler(crawler)
  • @abarnert 添加了整个管道类。
  • 不在管道类中。实际的调用代码在 Scrapy 内部,但是您需要一些代码来告诉它要构造哪些类以及将它们连接起来的顺序,而这就是您没有向我们展示的代码。我写了一个答案,试图用一般术语解释发生了什么,但如果你给我们minimal reproducible example,你会更容易理解。

标签: python scrapy


【解决方案1】:

类方法的调用者必须有一个类的实例。他们可能只是按名称访问它,如下所示:

DynamicSQLlitePipeline.from_crawler(crawler)

… 或:

sqlitepipeline.DynamicSQLlitePipeline.from_crawler(crawler)

或者,也许您将类对象传递给某人,然后他们将其存储并在以后使用,如下所示:

pipelines[i].from_crawler(crawler)

在 Scrapy 中,根据the docs 向框架注册一组管道的常用方法是这样的:

ITEM_PIPELINES = {
    'myproject.pipelines.PricePipeline': 300,
    'myproject.pipelines.JsonWriterPipeline': 800,
}

(另见Extensions user guide,它解释了它如何适合一个scrapy项目。)

大概您在未向我们展示的代码中做了类似的事情,在该字典中输入了类似'sqlscraper.pipelines.DynamicSQLlitePipeline' 的内容。在某些时候,Scrapy 会遍历该字典,按值对其进行排序,然后实例化每个管道。 (因为它有类的名称,作为一个字符串,而不是类对象,这有点棘手,但这里的细节真的不相关。)

【讨论】:

  • @user61629 酷。我确信有一个地方可以解释这一点,而不仅仅是提供参考,但我不确定它在哪里。因此,我已将您的发现编辑为答案。感谢您找到它。
  • 谢谢,我还发现以下有用的doc.scrapy.org/en/latest/topics/…。我不是 100% 理解 scrapy api 入口点,但我假设在实例化每个扩展(包括管道)之前,scrapy 调用了 from_crawler 类方法
  • @user61629 scrapy 的大部分内容并没有那么复杂,所以如果你想了解它的更多功能,你可以随时阅读the source。如果你用 grep 搜索 ITEM_PIPELINES 应该很容易找到。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-09
  • 2023-03-13
  • 1970-01-01
  • 2020-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多