python中级---->pymongo存储json数据

  这里面我们介绍一下python中操作mangodb的第三方库pymongo的使用,以及简单的使用requests库作爬虫。人情冷暖正如花开花谢,不如将这种现象,想成一种必然的季节。

pymongo的安装及前期准备

一、mangodb的安装以及启动

测试机器:win10, mangodb版本v3.4.0,python版本3.6.3。

mangodb的安装目录:D:\Database\DataBase\Mongo。数据的存放目录:E:\data\database\mango\data。首先我们启动mangodb服务器的:可以看到在本地27017端口成功启动server。

D:\Database\DataBase\Mongo\Server\3.4\bin>mongod --dbpath E:\data\database\mango\data
2017-11-21T20:48:38.458+0800 I CONTROL  [initandlisten] MongoDB starting : pid=20484 port=27017 dbpath=E:\data\database\mango\data 64-bit host=Linux
2017-11-21T20:48:38.461+0800 I CONTROL  [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2
2017-11-21T20:48:38.462+0800 I CONTROL  [initandlisten] db version v3.4.0
2017-11-21T20:48:38.463+0800 I CONTROL  [initandlisten] git version: f4240c60f005be757399042dc12f6addbc3170c1
2017-11-21T20:48:38.464+0800 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.1t-fips  3 May 2016
2017-11-21T20:48:38.465+0800 I CONTROL  [initandlisten] allocator: tcmalloc
2017-11-21T20:48:38.466+0800 I CONTROL  [initandlisten] modules: none
2017-11-21T20:48:38.466+0800 I CONTROL  [initandlisten] build environment:
2017-11-21T20:48:38.467+0800 I CONTROL  [initandlisten]     distmod: 2008plus-ssl
2017-11-21T20:48:38.468+0800 I CONTROL  [initandlisten]     distarch: x86_64
2017-11-21T20:48:38.469+0800 I CONTROL  [initandlisten]     target_arch: x86_64
2017-11-21T20:48:38.469+0800 I CONTROL  [initandlisten] options: { storage: { dbPath: "E:\data\database\mango\data" } }
2017-11-21T20:48:38.491+0800 I -        [initandlisten] Detected data files in E:\data\database\mango\data created by the ‘wiredTiger‘ storage engine, so setting the active storage engine to ‘wiredTiger‘.
2017-11-21T20:48:38.493+0800 I STORAGE  [initandlisten] wiredtiger_open config: create,cache_size=5573M,session_max=20000,eviction=(threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),checkpoint=(wait=60,log_size=2GB),statistics_log=(wait=0),
2017-11-21T20:48:39.931+0800 I CONTROL  [initandlisten]
2017-11-21T20:48:39.933+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2017-11-21T20:48:39.936+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2017-11-21T20:48:39.940+0800 I CONTROL  [initandlisten]
2017-11-21T20:48:41.253+0800 I FTDC     [initandlisten] Initializing full-time diagnostic data capture with directory ‘E:/data/database/mango/data/diagnostic.data‘
2017-11-21T20:48:41.259+0800 I NETWORK  [thread1] waiting for connections on port 27017

mangodb客户端的启动:D:\Database\DataBase\Mongo\Server\3.4\bin\mongo.exe。双击即可运行

MongoDB shell version v3.4.0
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.0
Server has startup warnings:
2017-11-21T20:48:39.931+0800 I CONTROL  [initandlisten]
2017-11-21T20:48:39.933+0800 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2017-11-21T20:48:39.936+0800 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2017-11-21T20:48:39.940+0800 I CONTROL  [initandlisten]
>

二、python中pymongo的安装

pip install pymongo

这里简单的介绍一下pymongo的使用,这里面的代码是选自github的入门例子。

>>> import pymongo
>>> client = pymongo.MongoClient("localhost", 27017)
>>> db = client.test
>>> db.name
u‘test‘
>>> db.my_collection
Collection(Database(MongoClient(‘localhost‘, 27017), u‘test‘), u‘my_collection‘)
>>> db.my_collection.insert_one({"x": 10}).inserted_id
ObjectId(‘4aba15ebe23f6b53b0000000‘)
>>> db.my_collection.insert_one({"x": 8}).inserted_id
ObjectId(‘4aba160ee23f6b543e000000‘)
>>> db.my_collection.insert_one({"x": 11}).inserted_id
ObjectId(‘4aba160ee23f6b543e000002‘)
>>> db.my_collection.find_one()
{u‘x‘: 10, u‘_id‘: ObjectId(‘4aba15ebe23f6b53b0000000‘)}
>>> for item in db.my_collection.find():
...     print(item["x"])
...
10
8
11
>>> db.my_collection.create_index("x")
u‘x_1‘
>>> for item in db.my_collection.find().sort("x", pymongo.ASCENDING):
...     print(item["x"])
...
8
10
11
>>> [item["x"] for item in db.my_collection.find().limit(2).skip(1)]
[8, 11]

pymongo的使用例子

一、python爬虫以及pymongo存储数据

import requests
import pymongo
import json

def requestData():
    url = ‘http://****.com/*.do‘
    data = {
        ‘projectId‘: 90,
        ‘myTaskFlag‘: 1,
        ‘userId‘: 40
    }
    json_data = requests.post(url, data=json.dumps(data)).json()
    return json_data

def output_data(json_data):
    client = pymongo.MongoClient(host=‘localhost‘, port=27017)
    db = client.test
    collection = db.tasks
    tasks_data = json_data.get(‘taskList‘)
    collection.insert(tasks_data)

if __name__ == ‘__main__‘:
    json_data = requestData()
    output_data(json_data)

我们把得到的数据存放在tasks集合中,这里使用的是mangodb默认的test数据库。运行完程序,我们可以通过mangodb的客户端查看数据,运行:db.tasks.find().pretty()可以查询tasks集合的所有数据。

{
        "_id" : ObjectId("5a1427a2edc9f04be40bc02d"),
        "taskId" : 1,
        "summary" : "PC版“个人信息”页面优化",
        "status" : 8,
        "categoryId" : 3,
        "creatorId" : 7,
        "projectId" : 1,
        "dateSubmit" : NumberLong("1481105108000"),
        "level" : 1,
        "handlerId" : 2,
        "ViewState" : 2,
        "priority" : 2
} {
        "_id" : ObjectId("5a1427a2edc9f04be40bc02e"),
        "taskId" : 2,
        "summary" : "PC版“添加新任务”界面字体太大",
        "status" : 8,
        "categoryId" : 3,
        "creatorId" : 7,
        "projectId" : 1,
        "dateSubmit" : NumberLong("1481105195000"),
        "level" : 1,
        "handlerId" : 2,
        "ViewState" : 2,
        "priority" : 1
}

友情链接

时间: 2024-08-26 12:04:43

python中级---->pymongo存储json数据的相关文章

使用Python Yaml包处理Json数据

在做网络爬虫的时候会遇到json数据格式的数据包,如果返回的是一个json格式的文件,可以使用 Python Yaml包处理数据,不需要再使用正则表达式匹配了,使用实例如 https://maps-api-ssl.google.com/maps/suggest?q=hello  这个地址,我们需要query对应的数据项. 相关代码如下: # -*- coding: utf-8 -*- import yaml import urllib2 address = 'https://maps-api-s

PHP处理来自Python的Post的json数据

最近用Python处理了一些json数据,但在过程中遇到一些问题,遂记录之. 1.Python Post json格式数据至服务器: 查阅了一些资料,大多是这么样的: __author__ = 'jiezhi' import urllib import urllib2 data = {'name': 'jiezhi', 'age': '24'} ret = urllib2.urlopen(url='http://jiezhiblog.com/test.php', data=urllib.urle

HTML5 LocalStorage 本地存储JSON数据

JSON数据存储在本地,需调用JSON.stringify()将其转为字符串.读取出来后调用JSON.parse()将字符串转为json格式.如写入的时候: var json_data = {id:12,name:"yang",email:"[email protected]"}; storage.setItem("json_data",JSON.stringify(json_data)); 读取的时候: var json_data = JSON

python#读csv,excel,json数据

1 #读csv,excel,json数据 2 with open('E:\\test\\xdd.csv','r') as f: 3 for line in f.readlines(): 4 print(line) 5 6 7 import pandas 8 df = pandas.read_csv('E:\\test\\xdd.csv') 9 print(df) 10 11 import pandas 12 df = pandas.read_excel('E:\\test\\aa.xls') 1

python爬虫中涉及json数据的处理

在执行爬虫项目的过程中,有时返回的不是一个html页面而是json格式数据,此时对数据的解析非常重要. 1.Json格式数据的爬取   采用request对以上的url进行爬取: import  requests content=requests.get(url,headers=headers).content 在爬取的过程中,考虑到需要模拟真实的用户,因此需要添加cookie或者header参数. 2.对爬取的json格式数据的解析 数据已经爬取下来,存放在contend里面,接下来就是对数据

python 读取单所有json数据写入mongodb(单个)

<--------------主函数-------------------> from pymongo import MongoClientfrom bson.objectid import ObjectIdfrom read_json import read def mongoclient(): client = MongoClient('127.0.0.1', 27017) db = client.test collection = db.test # collection.insert(

python提取网页中json数据

用法示例: 相对于python解析XML来说,我还是比较喜欢json的格式返回,现在一般的api返回都会有json与XML格式的选择,json的解析起来个人觉得相对简单些 先看一个简单的豆瓣的图书查询的api返回 http://api.douban.com/v2/book/isbn/9787218087351 {"rating":{"max":10,"numRaters":79,"average":"9.1"

python 处理 json 数据

1.通过json包处理json数据 import json #导入json包 json.dumps() # 将字典.列表转化为json格式的字符串 json.loads() #将json 格式的字符串转化为python 对象 json.dump(lt,open('json.txt','w',encoding='utf8')) #将lt 转化为json 格式的字符串写入到文件当中 json.load(open('json.txt','r',encoding='utf8')) #从文件中读取json

python爬取微博图片数据存到Mysql中遇到的各种坑\python Mysql存储图片

本人长期出售超大量微博数据,并提供特定微博数据打包,Message to [email protected] 前言   由于硬件等各种原因需要把大概170多万2t左右的微博图片数据存到Mysql中.之前存微博数据一直用的非关系型数据库mongodb,由于对Mysql的各种不熟悉,踩了无数坑,来来回回改了3天才完成. 挖坑填坑之旅 建表 存数据的时候首先需要设计数据库,我准备设计了3个表 微博表:[id, userid, blog_text, lat, lng, created_time, res