爬虫需要存储大量的数据,有时返回的数据都是json格式,这时选用NoSQL数据库存储就方便很多了。MongoDB是一个基于分布式文件存储的数据库,本身就为web应用提供了可扩展的高性能数据存储,在爬虫中使用MongoDB可以提供不少便利。
一、安装
下载地址:https://www.mongodb.com/download-center/community,下载完成后按步骤安装即可。
安装完毕之后,在cmd中运行一下,如下图
二、配置
以管理员身份运行cmd,执行命令:mongod --logpath "D:\Program Files\MongoDB\Server\4.0\log\mongod.log" --logappend --dbpath "d:\Program Files\MongoDB\Server\4.0\data\db" --port 27017 --serviceName "MongoDB" --serviceDisplayName "MongoDB" --install
这样就安装完mongodb的服务了。在浏览器里打开localhost:27017
看到这行字就是配置成功了。
三、python操作mongodb
1、安装pymongo库
pip install pymongo
2、连接数据库
import pymongo
client = pymongo.MongoClient(host='localhost',port=27017)
3、插入数据
插入一个叫张三的20岁的学生信息。
db = client.test
collection = db.students
student = {
'id':123,
'name':'张三',
'age':20
}
result = collection.insert(student)
print(result)
运行结果为
注:在新版的pymongo里,官方推荐使用insert_one()和insert_many()方法来分别插入单条数据和多条数据。
4、查询数据
result = collection.find_one({'name':'张三'})
print(result)
运行结果
查年龄的话,还可以通过大于小于
小于 | {<key>:{$lt:<value>}} | db.collcection.find({"age":{$lt:50}}) | where age< 50 |
小于或等于 | {<key>:{$lte:<value>}} | db.collcection.find({"age":{$lte:50}}) | where age <= 50 |
大于 | {<key>:{$gt:<value>}} | db.collection.find({"age":{$gt:50}}) | where age > 50 |
大于或等于 | {<key>:{$gte:<value>}} | db.collection.find({"age":{$gte:50}}) | where age >= 50 |
不等于 | {<key>:{$ne:<value>}} | db.collection.find({"age":{$ne:50}}) | where age != 50 |
5、更新数据
把张三的年龄改成18岁
student = collection.find_one({'name':'张三'})
student['age'] = 18
result = collection.update({'name':'张三'},student)
print(result)
运行结果
6、删除数据
result = collection.remove({'name':'张三'})
print(result)
运行结果
四、图形化界面
我选择了RoboMongo,下载地址:https://robomongo.org/download
下载完成后,配置一下host和port
然后就可以看到数据库里的数据了