当你启动一个scrapy项目时,你会得到一个这样的目录树:
$ scrapy startproject multipipeline
$ tree
.
├── multipipeline
│ ├── __init__.py
│ ├── items.py
│ ├── middlewares.py
│ ├── pipelines.py
│ ├── settings.py
│ └── spiders
│ ├── example.py
│ └── __init__.py
└── scrapy.cfg
而生成的pipelines.py 看起来像这样:
$ cat multipipeline/pipelines.py
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class MultipipelinePipeline(object):
def process_item(self, item, spider):
return item
但是你的 scrapy 项目可以引用任何 Python 类作为项目管道。一种选择是将生成的单文件pipelines 模块转换为它自己目录中的一个包,其中包含子模块。
注意pipelines/ 目录中的__init__.py 文件:
$ tree
.
├── multipipeline
│ ├── __init__.py
│ ├── items.py
│ ├── middlewares.py
│ ├── pipelines
│ │ ├── __init__.py
│ │ ├── one.py
│ │ ├── three.py
│ │ └── two.py
│ ├── settings.py
│ └── spiders
│ ├── example.py
│ └── __init__.py
└── scrapy.cfg
pipelines/ 目录中的各个模块可能如下所示:
$ cat multipipeline/pipelines/two.py
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import logging
logger = logging.getLogger(__name__)
class MyPipelineTwo(object):
def process_item(self, item, spider):
logger.debug(self.__class__.__name__)
return item
您可以阅读more about packages here。
__init__.py 文件是让 Python 处理
包含包的目录;这样做是为了防止
无意中使用通用名称(例如字符串)的目录
隐藏稍后出现在模块搜索路径上的有效模块。在
最简单的情况,__init__.py 可以只是一个空文件,但它可以
还执行包的初始化代码或设置__all__
变量,稍后介绍。
您的settings.py 将包含以下内容:
ITEM_PIPELINES = {
'multipipeline.pipelines.one.MyPipelineOne': 100,
'multipipeline.pipelines.two.MyPipelineTwo': 200,
'multipipeline.pipelines.three.MyPipelineThree': 300,
}