python金融大數(shù)據(jù)挖掘與分析(三)——Python與MySQL數(shù)據(jù)庫(kù)交互

@[toc]

1. MySQL與python庫(kù)準(zhǔn)備

這里推薦使用一款A(yù)pache Web服務(wù)器、PHP解釋器以及MySQL數(shù)據(jù)庫(kù)的整合軟件包——WampServer,其會(huì)自動(dòng)將一些設(shè)置配置好,無(wú)需配置環(huán)境變量,而且能夠使用MySQL的數(shù)據(jù)庫(kù)管理平臺(tái)phpMyAdmin,安裝過(guò)程很簡(jiǎn)單,大家可以到下面的鏈接地址下載相應(yīng)的軟件即可。
WampServer下載地址https://sourceforge.net/projects/wampserver/files/WampServer%203/WampServer%203.0.0/

為了實(shí)現(xiàn)Python和MySQL數(shù)據(jù)庫(kù)的交互,需要安裝PyMySQL庫(kù)。常規(guī)的安裝方法,pip install pymysql

2. 用python連接數(shù)據(jù)庫(kù)

通過(guò)以下代碼就能實(shí)現(xiàn)數(shù)據(jù)庫(kù)連接

import pymysql
db = pymysql.connect(host='localhost', port=3308, user='root', password='',
                         database='spider', charset='utf8')
# 其中spider為已創(chuàng)建的數(shù)據(jù)庫(kù)名稱
在這里插入圖片描述

3. 用python存儲(chǔ)數(shù)據(jù)到數(shù)據(jù)庫(kù)

在python中模擬執(zhí)行SQL語(yǔ)句需要首先引入一個(gè)會(huì)話指針cursor,只有這樣才能調(diào)用SQL語(yǔ)句。之后編寫(xiě)SQL語(yǔ)句,并通過(guò)cursor的execute函數(shù)執(zhí)行SQL語(yǔ)句。之后需要通過(guò)db.commit()函數(shù)來(lái)更新數(shù)據(jù)表,最后關(guān)閉之前引入的會(huì)話指針cur和數(shù)據(jù)庫(kù)連接。

    cur = db.cursor()      # 獲取會(huì)話指針,用來(lái)調(diào)用SQL語(yǔ)句
    sql = 'INSERT INTO test(company, title, href, date, source) VALUES (%s, %s, %s, %s, %s)'
    cur.execute(sql, (company, title, href, date, source))
    db.commit()
    
    cur.close()
    db.close()

上面的第三行代碼中,第一個(gè)參數(shù)為SQL語(yǔ)句,第二個(gè)參數(shù)用來(lái)把具體的內(nèi)容傳遞到各個(gè)%s的位置上。插入語(yǔ)句的整體代碼如下所示:

    # 預(yù)定義參數(shù)
    company = '阿里巴巴'
    title = '測(cè)試標(biāo)題'
    href = '測(cè)試鏈接'
    source = '測(cè)試來(lái)源'
    date = '測(cè)試時(shí)間'

    db = pymysql.connect(host='localhost', port=3308, user='root', password='',
                         database='spider', charset='utf8')

    cur = db.cursor()      # 獲取會(huì)話指針,用來(lái)調(diào)用SQL語(yǔ)句
    sql = 'INSERT INTO test(company, title, href, date, source) VALUES (%s, %s, %s, %s, %s)'
    cur.execute(sql, (company, title, href, date, source))
    db.commit()

    cur.close()
    db.close()

4. 用python在數(shù)據(jù)庫(kù)中查找并提取數(shù)據(jù)

這里的操作代碼與數(shù)據(jù)插入的代碼類似。

    db = pymysql.connect(host='localhost', port=3308, user='root', password='',
                         database='spider', charset='utf8')

    cur = db.cursor()      # 獲取會(huì)話指針,用來(lái)調(diào)用SQL語(yǔ)句
    sql = 'SELECT * FROM `test` WHERE company = %s'
    cur.execute(sql, company)
    data = cur.fetchall()
    print(data)
    db.commit()

    cur.close()
    db.close()

這里的db.commit()操作可以省略,因?yàn)椴簧婕皵?shù)據(jù)更新的操作。數(shù)據(jù)查詢中最重要的操作是cur.fetchall(),提取所有數(shù)據(jù),返回的結(jié)果為元組形式。

5. 用python從數(shù)據(jù)庫(kù)中刪除數(shù)據(jù)

操作類似,不再贅述。

    db = pymysql.connect(host='localhost', port=3308, user='root', password='',
                         database='spider', charset='utf8')

    cur = db.cursor()      # 獲取會(huì)話指針,用來(lái)調(diào)用SQL語(yǔ)句
    sql = 'DELETE FROM `test` WHERE company = %s'
    cur.execute(sql, company)
    db.commit()

    cur.close()
    db.close()

6. 把金融數(shù)據(jù)存入數(shù)據(jù)庫(kù)

這里結(jié)合本章內(nèi)容和之前的內(nèi)容(python金融大數(shù)據(jù)挖掘與分析(二)——新聞數(shù)據(jù)挖掘),實(shí)現(xiàn)將網(wǎng)絡(luò)獲取的新聞?lì)A(yù)料內(nèi)容存入數(shù)據(jù)庫(kù)。
數(shù)據(jù)庫(kù)操作類:

"""
    作者:Aidan
    時(shí)間:01/02/2020
    功能:python與mysql數(shù)據(jù)庫(kù)交互
"""
import pymysql
class database_execute(object):
    """
        數(shù)據(jù)庫(kù)操作類
    """
    def __init__(self, db_name):
        self.db_name = db_name

    def connect_db(self):
        db = pymysql.connect(host='localhost', port=3308, user='root', password='',
                                  database=self.db_name, charset='utf8')
        return db

    def insert_db(self, company, title, href, date, source):
        db = self.connect_db()
        cur = db.cursor()
        sql = 'INSERT INTO test(company, title, href, date, source) VALUES (%s, %s, %s, %s, %s)'
        cur.execute(sql, (company, title, href, date, source))
        db.commit()
        cur.close()
        db.close()

百度新聞爬蟲(chóng)函數(shù)

"""
    作者:Aidan
    時(shí)間:01/02/2020
    功能:提取百度新聞標(biāo)題、網(wǎng)址、日期和來(lái)源
    新增功能,批量獲取多家公司的百度新聞并生成數(shù)據(jù)報(bào)告
"""

import requests
import re

def baidu_news(company):
    """
    獲取網(wǎng)頁(yè)源碼,并提取百度新聞標(biāo)題、網(wǎng)址、日期和來(lái)源
    :param company: 公司名稱
    :return: 網(wǎng)頁(yè)源碼
    """
    url = 'https://www.baidu.com/s?rtt=1&bsst=1&cl=2&tn=news&word=' + company
    # 百度新聞網(wǎng)站只認(rèn)可瀏覽器發(fā)送的請(qǐng)求,所以需要設(shè)置headers參數(shù),
    # 以模擬瀏覽器的發(fā)送請(qǐng)求,chrome瀏覽器可以通過(guò)about:version獲取
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                             'AppleWebKit/537.36 (KHTML, like Gecko) '
                             'Chrome/77.0.3865.120 Safari/537.36'}
    res = requests.get(url, headers=headers)
    web_text = res.text

    # 獲取新聞的來(lái)源和日期
    pattern = '<p class="c-author">(.*?)</p>'
    info = re.findall(pattern, web_text, re.S)  # re.S用于考慮換行符,因?yàn)?和*不包含換行符
    # print(info)

    # 獲取新聞的網(wǎng)址和標(biāo)題
    pattern_herf = '<h3 class="c-title">.*?<a href="(.*?)"'
    href = re.findall(pattern_herf, web_text, re.S)
    # print(href)

    pattern_title = '<h3 class="c-title">.*?>(.*?)</a>'
    title = re.findall(pattern_title, web_text, re.S)
    # print(title)

    # title 數(shù)據(jù)清洗
    for i in range(len(title)):
        title[i] = title[i].strip()
        title[i] = re.sub('<.*?>', '', title[i])

    # print(title)

    # 新聞來(lái)源和日期清洗
    source = []
    date = []

    for i in range(len(info)):
        info[i] = re.sub('<.*?>', '', info[i])  # 清洗<img>標(biāo)簽信息
        source.append(info[i].split('&nbsp;&nbsp;')[0])  # 將新聞來(lái)源和日期分開(kāi)
        date.append(info[i].split('&nbsp;&nbsp;')[1])
        source[i] = source[i].strip()
        date[i] = date[i].strip()

    return title, href, date, source

主函數(shù)

import spider
import python_database

def main():

    companys = ['華能信托', '騰訊', '阿里巴巴']
    title = []
    href = []
    date = []
    source = []

    db_connect = python_database.database_execute('spider')

    for company in companys:
        try:
            title, href, date, source = spider.baidu_news(company)
            for i in range(len(title)):
                db_connect.insert_db(company, title[i], href[i], date[i], source[i])
            print(company + '百度新聞爬取成功!')
        except:
            print(company + '百度新聞爬取失敗!')

if __name__ == '__main__':
    main()

執(zhí)行結(jié)果如下:


在這里插入圖片描述
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容