scrapy框架之pipelines模块总结和注意事项

 项目目录scrapy_first/settings.py配置文件设置

scrapy_first/pipelines.py文件下实现pipeline类

实现Pipeline模块主要是实现四个方法!

class BookFilterPipeline:

    def __init__(self, count):
        self.count = count

    (必须实现的方法)处理item数据的函数---注意:item是一条数据,爬虫会自动循环调用!
    def process_item(self, item, spider):
        if item["rating"] < self.count:
            raise DropItem("小于3的数据被过滤")
        return item

    (可选)此方法如果实现了,那么BookFilterPipeline对象从这里调用,必须返回一个cls(参数)对象
    crawler.settings是读取项目目录下的settings中的配置选项!
    @classmethod
    def from_crawler(cls, crawler):
        读取配置文件的数据

        count = crawler.settings.get('BOOK_FILTER_COUNT', 0)
        返回实例化对象
        return cls(count)

    (可选)打开蜘蛛时会调用此方法。
    def open_spider(self, spider):
        self.file = open('items.jl', 'w')

    (可选)当蜘蛛关闭时调用此方法。
    def close_spider(self, spider):
        self.file.close()

 

猜你喜欢

转载自blog.csdn.net/weixin_43343144/article/details/87896487