请选择 进入手机版 | 继续访问电脑版

笨鸟编程-零基础入门Pyhton教程

 找回密码
 立即注册

项目管道

发布者: 笨鸟自学网



将项目写入MongoDB

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

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

import pymongo
from itemadapter import ItemAdapter

class MongoPipeline:

    collection_name = 'scrapy_items'

    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def 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_one(ItemAdapter(item).asdict())
        return item

项目截图

这个例子演示了如何使用 coroutine syntax 在 process_item() 方法。

此项管道向本地运行的实例发出请求 Splash 呈现项目URL的屏幕截图。下载请求响应后,项目管道将屏幕截图保存到文件中,并将文件名添加到项目中。

import hashlib
from urllib.parse import quote

import scrapy
from itemadapter import ItemAdapter
from scrapy.utils.defer import maybe_deferred_to_future


class ScreenshotPipeline:
    """Pipeline that uses Splash to render screenshot of
    every Scrapy item."""

    SPLASH_URL = "http://localhost:8050/render.png?url={}"

    async def process_item(self, item, spider):
        adapter = ItemAdapter(item)
        encoded_item_url = quote(adapter["url"])
        screenshot_url = self.SPLASH_URL.format(encoded_item_url)
        request = scrapy.Request(screenshot_url)
        response = await maybe_deferred_to_future(spider.crawler.engine.download(request, spider))

        if response.status != 200:
            # Error happened, return item.
            return item

        # Save screenshot to file, filename will be hash of url.
        url = adapter["url"]
        url_hash = hashlib.md5(url.encode("utf8")).hexdigest()
        filename = f"{url_hash}.png"
        with open(filename, "wb") as f:
            f.write(response.body)

        # Store filename in item.
        adapter["screenshot_filename"] = filename
        return item 

上一篇:Scrapy shell下一篇:Feed 导出

Archiver|手机版|笨鸟自学网 ( 粤ICP备20019910号 )

GMT+8, 2024-12-5 23:13 , Processed in 0.085045 second(s), 17 queries .

© 2001-2020

返回顶部