数据库

数据库实际

 

1、Python MongoDB

MongoDB 是目前最流行的 NoSQL 数据库之一,使用的数据类型 BSON(类似 JSON)。

MongoDB 数据库安装与介绍可以查看我们的 MongoDB 教程。

2、SQLite - Python

安装

SQLite3 可使用 sqlite3 模块与 Python 进行集成。sqlite3 模块是由 Gerhard Haring 编写的。它提供了一个与 PEP 249 描述的 DB-API 2.0 规范兼容的 SQL 接口。您不需要单独安装该模块,因为 Python 2.5.x 以上版本默认自带了该模块。

为了使用 sqlite3 模块,您首先必须创建一个表示数据库的连接对象,然后您可以有选择地创建光标对象,这将帮助您执行所有的 SQL 语句。

Python sqlite3 模块 API

以下是重要的 sqlite3 模块程序,可以满足您在 Python 程序中使用 SQLite 数据库的需求。如果您需要了解更多细节,请查看 Python sqlite3 模块的官方文档。

首先我们介绍MongoDb

PyMongo

Python 要连接 MongoDB 需要 MongoDB 驱动,这里我们使用 PyMongo 驱动来连接。

pip 安装

pip 是一个通用的 Python 包管理工具,提供了对 Python 包的查找、下载、安装、卸载的功能。

安装 pymongo:

在命令行中用pip安装  输入代码:

$ python3 -m pip3 install pymongo

 

 

 

实例运用——爬取中国大学排名并写入数据库,外加查询and创新

  爬取过程中到的数据写入数据库

复制代码
复制代码
from bs4 import BeautifulSoup
import requests
import pandas as pd
import pymongo

def client_Mongodb(port, path):
    myclient = pymongo.MongoClient(host='localhost', port=port)  # 连接
    my_set = myclient.path  # 连接path,如果没有则创建一个数据库
    return my_set

def save_mongo(result):
    myclient = pymongo.MongoClient(host='localhost', port=27017)
    my_set = myclient.University.ranking
    try:
        if my_set.product.insert_one(result): #如果保存成功
            pass#print("数据保存成功")
    except Exception:
        print("数据保存失败")

def save_list_to_Mongodb(lists):
    my_set = client_Mongodb(27017, 'University.ranking')
    product = {
        '排名': lists[0],
        '学校名称': lists[1],
        '省份': lists[2],
        '总分': lists[3],
        '生源质量(新生高考成绩得分)': lists[4],
        '培养结果(毕业生就业率': lists[5],
        '社会声誉(社会捐赠收入·千元': lists[6],
        '科研规模(论文数量·篇)': lists[7],
        '科研质量(论文质量·FWCI)': lists[8],
        '顶尖成果(高被引论文·篇)': lists[9],
        '顶尖人才(高被引学者·人)': lists[10],
        '科技服务(企业科研经费·千元': lists[11],
        '成果转化(技术转让收入·千元)': lists[12],
        '学生国际化(留学生比例)': lists[13],
        }  # 字典类型数据
    save_mongo(product)

def getHTMLText(url):
    try:
        r = requests.get(url, timeout=10)
        r.raise_for_status()
        r.encoding = 'utf-8'
        return r.text
    except:
        return ""

def filUnivList(soup):
    data = soup.find_all('tr')
    for tr in data:
        ltd = tr.find_all('td')
        if len(ltd) == 0:
            continue
        singleUniv = []
        for td in ltd:
            singleUniv.append(td.string)
        save_list_to_Mongodb(singleUniv)

def main():
    url = 'http://www.zuihaodaxue.cn/zuihaodaxuepaiming2019.html'
    html = getHTMLText(url)
    soup = BeautifulSoup(html, "html.parser")
    filUnivList(soup)
    print("完成")
    for i in pymongo.MongoClient(host='localhost', port=27017).University.ranking.product.find():
        print(i)  # 输出
main()
复制代码
 
 
 

 

 

复制代码

结果:

posted @ 2019-05-30 00:00  英瀚也很外向哦  阅读(125)  评论(0编辑  收藏  举报