scrapy框架中item pipeline应用

1、item pipeline说明

编写item pipeline很简单,item pipiline组件是一个独立的Python类,其中process_item()方法必须实现:

import something

class SomethingPipeline(object):
    def __init__(self):    
        # 可选实现,做参数初始化等
        # doing something

    def process_item(self, item, spider):
        # item (Item 对象) – 被爬取的item
        # spider (Spider 对象) – 爬取该item的spider
        # 这个方法必须实现,每个item pipeline组件都需要调用该方法,
        # 这个方法必须返回一个 Item 对象,被丢弃的item将不会被之后的pipeline组件所处理。
        return item

    def open_spider(self, spider):
        # spider (Spider 对象) – 被开启的spider
        # 可选实现,当spider被开启时,这个方法被调用。

    def close_spider(self, spider):
        # spider (Spider 对象) – 被关闭的spider
        # 可选实现,当spider被关闭时,这个方法被调用

2、图片管道ImagesPipeline

首先这个ImagesPipeline是scrapy自带的类,用来处理图片(爬取时将图片下载到本地)用的。

2.1、ImagesPipeline类的源码

ImagesPipeline类的部分源码截图:

 

2.2.、图片管道应用案例一:

1、settings.py文件配置

DEFAULT_REQUEST_HEADERS = {
  'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  'Accept-Language': 'en',
  'Referer' : 'http://www.angelimg.com' # 跨域图片问题,需要指定
}

ITEM_PIPELINES = {   
   'scrapy.pipelines.images.ImagesPipeline' : 300, # 图片管道
}

2、item.py文件配置 

import scrapy

class AngelItem(scrapy.Item):
    image_urls = scrapy.Field() # 图片管道必须字段
    images = scrapy.Field() # 图片管道必须字段
    pass

3、Json管道JsonLinesItemExporter

    JsonLinesItemExporter:每次调用export_item的时候就把这个item存储到磁盘中.坏处是一个字典一行,整个文件不是一个满足json格式的文件.好处是每次数据都直接存到磁盘文件中,不会耗内存,数据相对安全。

3.1、简单json文件写入

import json

class ItcastJsonPipeline(object):

    def __init__(self):
        self.file = open('teacher.json', 'wb')

    def process_item(self, item, spider):
        content = json.dumps(dict(item), ensure_ascii=False) + "\n"
        self.file.write(content)
        return item

    def close_spider(self, spider):
        self.file.close()

3.2、JsonLinesItemExporter管道应用

扫描二维码关注公众号,回复: 6418171 查看本文章

使用Json管道功能需要导入from scrapy.exporters import JsonLinesItemExporter

pipelines.py

# -*- coding: utf-8 -*-
from scrapy.exporters import JsonLinesItemExporter

class FangPipeline(object):
    def __init__(self):
        self.newhouse_fp = open("newhouse.json","wb")
        self.esfhouse_fp = open("esfhouse.json","wb")
        self.newhouse_exporter = JsonLinesItemExporter(self.newhouse_fp,ensure_ascii=False)
        self.esfhouse_exporter = JsonLinesItemExporter(self.esfhouse_fp,ensure_ascii=False)

    def process_item(self, item, spider):
       self.newhouse_exporter.export_item(item)
       self.esfhouse_exporter.export_item(item)
       return item

    def close_spider(self, spider):
        self.newhouse_fp.close()
        self.esfhouse_fp.close()

猜你喜欢

转载自blog.csdn.net/u013089490/article/details/91368640