python爬虫之MongoDB

如果各位真的想学习爬虫,那么肯定会用到数据库,下面为大家简单介绍一下MongoDB数据库,以及一些简单的配置,这里有一个MongoDB的可视化工具,大家若需要的话可以下载一下https://github.com/nidexiaogege/application/blob/master/robo3t-1.1.1-windows-x86_64-c93c6b0.exe
使用MongoDB进行存储首先进行配置,
第一步:导入需要的类库

import pickle  # 对象序列化
import zlib  # 压缩数据
from datetime import datetime,timedelta  # 设置缓存超时间隔
from pymongo import MongoClient
from bson.binary import Binary  # MongoDB存储二进制的类型

第二步:可以使用python面向对象的理念,先创建一个mongocache类

class MongoCache(object):
    """
    数据库缓存
    """
    def __init__(self,client=None,expires=timedelta(days=30)):
        """
        初始化函数
        :param client:数据库连接
        :param expires: 超时时间
        """
        self.client = MongoClient(host='localhost',port=27017)
        self.db = self.client.cache # 创建一个名为cache的数据库
        web_page = self.db.webpage # 创建webpage这个表(collection)
        # 创建timestamp索引,设置超时时间位30天(会转化为秒)
        self.db.webpage.create_index('timestamp',expireAfterSeconds=expires.total_seconds())

第三步:实现向数据库添加数据

def __setitem__(self, key, value):
        """
        向数据库添加一条缓存(数据)
        :param key: 缓存关键字
        :param value: 缓存内容
        :return:
        """
        # 将数据使用pickl序列化,在使用zlib压缩且转换为Binary格式,使用格林威治时间
        record = {'result':Binary(zlib.compress(pickle.dumps(value))),'timestamp':datetime.utcnow()}
        # 使用下载的url作为key,存入系统默认生成的_id字段,存入数据库
        self.db.webpage.update({'_id':key},{'$set':record},upsert=True)

第四步:实现从数据库查找数据

def __getitem__(self, item):
        """
        将缓存数据按照item作为key取出(key仍然使下载的url)
        :param item:
        :return:
        """
        record = self.db.webpage.find_one({'_id':item})
        if record:
            return pickle.loads(zlib.decompress(record['result']))
        else:
            raise KeyError(item + 'does not exist')
            def __contains__(self, item):
        """
        调用 in 或 not in 时会调用该函数判断连接对应网址是否在数据库中
        :param item: 下载的url连接
        :return:
        """
        try:
            self[item]
        except KeyError:
            return False
        else:
            return True

第五步;实现清空数据库

def clear(self):
        # 全部清空
        self.db.webpage.dorp()

全部完成之后就可以使用了,就像使用其他的python类库一样,通过导入之后创建对象即可使用。

猜你喜欢

转载自blog.csdn.net/oyjl19961216/article/details/82778256