欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

Scrapy-Item Pipeline(项目管道)

发布时间:2024/7/23 编程问答 47 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Scrapy-Item Pipeline(项目管道) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

 

Item Pipeline(英文版):http://doc.scrapy.org/en/latest/topics/item-pipeline.html

Item Pipeline(中文版):https://scrapy-chs.readthedocs.io/zh_CN/latest/topics/item-pipeline.html

Scrapy 1.3 文档  item Pipeline:https://oner-wv.gitbooks.io/scrapy_zh/content/基本概念/item管道.html

scrapy 多个pipeline:https://www.baidu.com/s?wd=scrapy 多个pipeline

不同的 spider item 如何指定不同的 pipeline处理?:https://segmentfault.com/q/1010000006890114?_ea=1166343

 

 

scrapy 源码 pipelines 目录下有三个文件:files.py、images.py、media.py 。scrapy 在这个三个文件中提供了三种不同的 pipeline 

  • media.py:class MediaPipeline(object):可以下载 媒体

  • files.py:class FilesPipeline(MediaPipeline):可以下载文件。FilesPipeline 继承 MediaPipeline
    Python3 scrapy下载网易云音乐所有(大部分)歌曲:https://blog.csdn.net/Heibaiii/article/details/79323634
  • images.py:class ImagesPipeline(FilesPipeline)。可以下载图片,也可以自己写 pipeline 下载图片
    使用 ImagesPipeline 下载图片:https://blog.csdn.net/freeking101/article/details/87860892
    下载壁纸图,使用ImagesPipeline:https://blog.csdn.net/qq_28817739/article/details/79904391
  •  

     

    Item Pipeline(项目管道)

     

    在项目被蜘蛛抓取后,它被发送到项目管道,它通过顺序执行的几个组件来处理它。

    每个项目管道组件(有时称为“Item Pipeline”)是一个实现简单方法的Python类。他们接收一个项目并对其执行操作,还决定该项目是否应该继续通过流水线或被丢弃并且不再被处理。

    项目管道的典型用途是:

    • 清理HTML数据
    • 验证抓取的数据(检查项目是否包含特定字段)
    • 检查重复(并删除)
    • 将刮取的项目存储在数据库中

     

     

    编写自己的项目管道

     

    每个项目管道组件是一个Python类

     

    process_item(self, item, spider)

    每个项目管道组件都必须调用此方法。process_item() 必须:返回一个带数据的dict,返回一个Item (或任何后代类)对象,返回一个Twisted Deferred或者raise DropItemexception。丢弃的项目不再由其他管道组件处理。

    参数:

    • item:( Itemobject 或 dict ) - 
    • Spider:自己编写的 Spider ,即自定义的 Spider 类的对象

     

    open_spider(self, spider):蜘蛛打开时调用 这个方法。

    参数:spider:自己编写的 Spider ,即自定义的 Spider 类的对象

     

    close_spider(self, spider):当蜘蛛关闭时调用此方法。

    参数:spider:自己编写的 Spider ,即自定义的 Spider 类的对象

     

    from_crawler(cls, crawler):

    如果存在,则此类方法被调用,通过 Crawler 来创建一个 pipeline 实例。它必须返回管道的新实例。Crawler对象 提供对所有Scrapy核心组件(如设置和信号)的访问,它是管道访问它们并将其功能挂钩到Scrapy中的一种方式。

    参数:crawler(Crawlerobject) - 使用此管道的 crawler

     

    爬虫示例:

    images.py:

    # -*- coding: utf-8 -*- from scrapy import Spider, Request from urllib.parse import urlencode import jsonfrom images360.items import ImageItemclass ImagesSpider(Spider):name = 'images'allowed_domains = ['images.so.com']start_urls = ['http://images.so.com/']def start_requests(self):data = {'ch': 'photography', 'listtype': 'new'}base_url = 'https://image.so.com/zj?'for page in range(1, self.settings.get('MAX_PAGE') + 1):data['sn'] = page * 30params = urlencode(data)url = base_url + paramsyield Request(url, self.parse)def parse(self, response):result = json.loads(response.text)for image in result.get('list'):item = ImageItem()item['id'] = image.get('imageid')item['url'] = image.get('qhimg_url')item['title'] = image.get('group_title')item['thumb'] = image.get('qhimg_thumb_url')yield item

    items.py:

    # -*- coding: utf-8 -*-# Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.htmlfrom scrapy import Item, Fieldclass ImageItem(Item):collection = table = 'images'id = Field()url = Field()title = Field()thumb = Field()

    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.htmlimport pymongo import pymysql from scrapy import Request from scrapy.exceptions import DropItem from scrapy.pipelines.images import ImagesPipelineclass MongoPipeline(object):def __init__(self, mongo_uri, mongo_db):self.mongo_uri = mongo_uriself.mongo_db = mongo_db@classmethoddef from_crawler(cls, crawler):return cls(mongo_uri=crawler.settings.get('MONGO_URI'),mongo_db=crawler.settings.get('MONGO_DB'))def open_spider(self, spider):self.client = pymongo.MongoClient(self.mongo_uri)self.db = self.client[self.mongo_db]def process_item(self, item, spider):name = item.collectionself.db[name].insert(dict(item))return itemdef close_spider(self, spider):self.client.close()class MysqlPipeline():def __init__(self, host, database, user, password, port):self.host = hostself.database = databaseself.user = userself.password = passwordself.port = port@classmethoddef from_crawler(cls, crawler):return cls(host=crawler.settings.get('MYSQL_HOST'),database=crawler.settings.get('MYSQL_DATABASE'),user=crawler.settings.get('MYSQL_USER'),password=crawler.settings.get('MYSQL_PASSWORD'),port=crawler.settings.get('MYSQL_PORT'),)def open_spider(self, spider):self.db = pymysql.connect(self.host, self.user, self.password, self.database, charset='utf8',port=self.port)self.cursor = self.db.cursor()def close_spider(self, spider):self.db.close()def process_item(self, item, spider):print(item['title'])data = dict(item)keys = ', '.join(data.keys())values = ', '.join(['%s'] * len(data))sql = 'insert into %s (%s) values (%s)' % (item.table, keys, values)self.cursor.execute(sql, tuple(data.values()))self.db.commit()return itemclass ImagePipeline(ImagesPipeline):def file_path(self, request, response=None, info=None):url = request.urlfile_name = url.split('/')[-1]return file_namedef item_completed(self, results, item, info):image_paths = [x['path'] for ok, x in results if ok]if not image_paths:raise DropItem('Image Downloaded Failed')return itemdef get_media_requests(self, item, info):yield Request(item['url'])

     

     

     

    项目管道示例

     

    价格验证和丢弃项目没有价格

     

    让我们来看看以下假设的管道,它调整 price那些不包括增值税(price_excludes_vat属性)的项目的属性,并删除那些不包含价格的项目:

    from scrapy.exceptions import DropItemclass PricePipeline(object):vat_factor = 1.15def process_item(self, item, spider):if item['price']:if item['price_excludes_vat']:item['price'] = item['price'] * self.vat_factorreturn itemelse:raise DropItem("Missing price in %s" % item)

    将项目写入JSON文件

    以下管道将所有抓取的项目(来自所有蜘蛛)存储到单个items.jl文件中,每行包含一个项目,以JSON格式序列化:

    import jsonclass JsonWriterPipeline(object):def open_spider(self, spider):self.file = open('items.jl', 'wb')def close_spider(self, spider):self.file.close()def process_item(self, item, spider):line = json.dumps(dict(item)) + "\n"self.file.write(line)return item

     

    注意

    JsonWriterPipeline的目的只是介绍如何编写项目管道。如果您真的想要将所有抓取的项目存储到JSON文件中,则应使用Feed导出。

     

     

    将项目写入MongoDB

     

    在这个例子中,我们使用pymongo将项目写入MongoDB。MongoDB地址和数据库名称在Scrapy设置中指定; MongoDB集合以item类命名。

    这个例子的要点是显示如何使用from_crawler()方法和如何正确清理资源:

    import pymongoclass MongoPipeline(object):collection_name = 'scrapy_items'def __init__(self, mongo_uri, mongo_db):self.mongo_uri = mongo_uriself.mongo_db = mongo_db@classmethoddef from_crawler(cls, crawler):return cls(mongo_uri=crawler.settings.get('MONGO_URI'),mongo_db=crawler.settings.get('MONGO_DATABASE', 'items'))def open_spider(self, spider):self.client = pymongo.MongoClient(self.mongo_uri)self.db = self.client[self.mongo_db]def close_spider(self, spider):self.client.close()def process_item(self, item, spider):self.db[self.collection_name].insert(dict(item))return item

     

    拍摄项目的屏幕截图

     

    此示例演示如何从方法返回Deferredprocess_item()。它使用Splash来呈现项目网址的屏幕截图。Pipeline请求本地运行的Splash实例。在请求被下载并且Deferred回调触发后,它将项目保存到一个文件并将文件名添加到项目。

    import scrapy import hashlib from urllib.parse import quoteclass ScreenshotPipeline(object):"""Pipeline that uses Splash to render screenshot ofevery Scrapy item."""SPLASH_URL = "http://localhost:8050/render.png?url={}"def process_item(self, item, spider):encoded_item_url = quote(item["url"])screenshot_url = self.SPLASH_URL.format(encoded_item_url)request = scrapy.Request(screenshot_url)dfd = spider.crawler.engine.download(request, spider)dfd.addBoth(self.return_item, item)return dfddef return_item(self, response, item):if response.status != 200:# Error happened, return item.return item# Save screenshot to file, filename will be hash of url.url = item["url"]url_hash = hashlib.md5(url.encode("utf8")).hexdigest()filename = "{}.png".format(url_hash)with open(filename, "wb") as f:f.write(response.body)# Store filename in item.item["screenshot_filename"] = filenamereturn item

     

    重复过滤器

     

    用于查找重复项目并删除已处理的项目的过滤器。假设我们的项目具有唯一的ID,但是我们的蜘蛛会返回具有相同id的多个项目:

    from scrapy.exceptions import DropItemclass DuplicatesPipeline(object):def __init__(self):self.ids_seen = set()def process_item(self, item, spider):if item['id'] in self.ids_seen:raise DropItem("Duplicate item found: %s" % item)else:self.ids_seen.add(item['id'])return item

     

    激活项目管道组件

     

    要激活项目管道组件,必须将其类添加到 ITEM_PIPELINES设置,类似于以下示例:

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

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

     

     

     

    总结

    以上是生活随笔为你收集整理的Scrapy-Item Pipeline(项目管道)的全部内容,希望文章能够帮你解决所遇到的问题。

    如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。