Scrapy - 激活项目管道组件 - ITEM_PIPELINES 设置

Inê*_*ins 3 python settings pipeline scrapy

scrapy文档中有这样的信息:

\n\n
\n

激活项目管道组件

\n\n

要激活项目管道组件,您必须将其类添加到\n ITEM_PIPELINES 设置,如以下示例所示:

\n\n

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

\n\n

您在此设置中分配给类的整数值决定了它们运行的​​顺序 - 项目从顺序号低到高的顺序通过管道。通常将这些数字定义在 0-1000 范围内。

\n
\n\n

我不明白最后一段,主要是“确定它们运行的​​顺序-项目从顺序号低到高的顺序通过管道”,你能换句话解释一下吗?选择这些数字的原因是什么?范围是0-1000如何选择值?

\n

ale*_*cxe 5

由于Python 中的字典是无序集合并且ITEM_PIPELINES必须是字典(与许多其他设置一样,例如 )SPIDER_MIDDLEWARES,因此您需要以某种方式定义应用管道的顺序。这就是为什么您需要为您定义的每个管道分配一个 0 到 1000 之间的数字。

仅供参考,如果您查看 Scrapy 源代码,您会发现build_component_list()为每个设置调用的函数,例如ITEM_PIPELINES- 它从您定义的字典中创建一个列表(有序集合),ITEM_PIPELINES使用字典值进行排序:

def build_component_list(base, custom):
    """Compose a component list based on a custom and base dict of components
    (typically middlewares or extensions), unless custom is already a list, in
    which case it's returned.
    """
    if isinstance(custom, (list, tuple)):
        return custom
    compdict = base.copy()
    compdict.update(custom)
    items = (x for x in six.iteritems(compdict) if x[1] is not None)
    return [x[0] for x in sorted(items, key=itemgetter(1))]
Run Code Online (Sandbox Code Playgroud)