数据分析Mysql

python金融大数据挖掘与分析(三)——Python与MySQ

2020-02-01  本文已影响0人  aidanmomo

@[toc]

1. MySQL与python库准备

这里推荐使用一款Apache Web服务器、PHP解释器以及MySQL数据库的整合软件包——WampServer,其会自动将一些设置配置好,无需配置环境变量,而且能够使用MySQL的数据库管理平台phpMyAdmin,安装过程很简单,大家可以到下面的链接地址下载相应的软件即可。
WampServer下载地址https://sourceforge.net/projects/wampserver/files/WampServer%203/WampServer%203.0.0/

为了实现Python和MySQL数据库的交互,需要安装PyMySQL库。常规的安装方法,pip install pymysql

2. 用python连接数据库

通过以下代码就能实现数据库连接

import pymysql
db = pymysql.connect(host='localhost', port=3308, user='root', password='',
                         database='spider', charset='utf8')
# 其中spider为已创建的数据库名称
在这里插入图片描述

3. 用python存储数据到数据库

在python中模拟执行SQL语句需要首先引入一个会话指针cursor,只有这样才能调用SQL语句。之后编写SQL语句,并通过cursor的execute函数执行SQL语句。之后需要通过db.commit()函数来更新数据表,最后关闭之前引入的会话指针cur和数据库连接。

    cur = db.cursor()      # 获取会话指针,用来调用SQL语句
    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()

上面的第三行代码中,第一个参数为SQL语句,第二个参数用来把具体的内容传递到各个%s的位置上。插入语句的整体代码如下所示:

    # 预定义参数
    company = '阿里巴巴'
    title = '测试标题'
    href = '测试链接'
    source = '测试来源'
    date = '测试时间'

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

    cur = db.cursor()      # 获取会话指针,用来调用SQL语句
    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在数据库中查找并提取数据

这里的操作代码与数据插入的代码类似。

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

    cur = db.cursor()      # 获取会话指针,用来调用SQL语句
    sql = 'SELECT * FROM `test` WHERE company = %s'
    cur.execute(sql, company)
    data = cur.fetchall()
    print(data)
    db.commit()

    cur.close()
    db.close()

这里的db.commit()操作可以省略,因为不涉及数据更新的操作。数据查询中最重要的操作是cur.fetchall(),提取所有数据,返回的结果为元组形式。

5. 用python从数据库中删除数据

操作类似,不再赘述。

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

    cur = db.cursor()      # 获取会话指针,用来调用SQL语句
    sql = 'DELETE FROM `test` WHERE company = %s'
    cur.execute(sql, company)
    db.commit()

    cur.close()
    db.close()

6. 把金融数据存入数据库

这里结合本章内容和之前的内容(python金融大数据挖掘与分析(二)——新闻数据挖掘),实现将网络获取的新闻预料内容存入数据库。
数据库操作类:

"""
    作者:Aidan
    时间:01/02/2020
    功能:python与mysql数据库交互
"""
import pymysql
class database_execute(object):
    """
        数据库操作类
    """
    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()

百度新闻爬虫函数

"""
    作者:Aidan
    时间:01/02/2020
    功能:提取百度新闻标题、网址、日期和来源
    新增功能,批量获取多家公司的百度新闻并生成数据报告
"""

import requests
import re

def baidu_news(company):
    """
    获取网页源码,并提取百度新闻标题、网址、日期和来源
    :param company: 公司名称
    :return: 网页源码
    """
    url = 'https://www.baidu.com/s?rtt=1&bsst=1&cl=2&tn=news&word=' + company
    # 百度新闻网站只认可浏览器发送的请求,所以需要设置headers参数,
    # 以模拟浏览器的发送请求,chrome浏览器可以通过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

    # 获取新闻的来源和日期
    pattern = '<p class="c-author">(.*?)</p>'
    info = re.findall(pattern, web_text, re.S)  # re.S用于考虑换行符,因为.和*不包含换行符
    # print(info)

    # 获取新闻的网址和标题
    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 数据清洗
    for i in range(len(title)):
        title[i] = title[i].strip()
        title[i] = re.sub('<.*?>', '', title[i])

    # print(title)

    # 新闻来源和日期清洗
    source = []
    date = []

    for i in range(len(info)):
        info[i] = re.sub('<.*?>', '', info[i])  # 清洗<img>标签信息
        source.append(info[i].split('&nbsp;&nbsp;')[0])  # 将新闻来源和日期分开
        date.append(info[i].split('&nbsp;&nbsp;')[1])
        source[i] = source[i].strip()
        date[i] = date[i].strip()

    return title, href, date, source

主函数

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()

执行结果如下:


在这里插入图片描述
上一篇下一篇

猜你喜欢

热点阅读