完整代码
实际上,整个事情完成了两个相对独立的过程:1.爬虫获取网页股票数据并保存到本地文件;2.将本地文件数据储存到MySQL数据库。并没有直接的考虑把从网页上抓取到的数据实时(或者通过一个临时文件)扔进数据库,跳过本地数据文件这个过程。这里只是尝试着去实现了一下这件事情,代码没有做任何的优化考虑。本身不实际去使用,只是乐趣而已,差不多先这样。哈哈~~
#导入需要使用到的模块
import urllib
import re
import pandas as pd
import pymysql
import os
#爬虫抓取网页函数
def getHtml(url):
html = urllib.request.urlopen(url).read()
html = html.decode('gbk')
return html
#抓取网页股票代码函数
def getStackCode(html):
s = r'
'#########################开始干活############################
Url = 'http://quote.eastmoney.com/stocklist.html'#东方财富网股票数据连接地址
filepath = 'C:\\Users\\Lenovo\\Desktop\\data\\'#定义数据文件保存路径
code = getStackCode(getHtml(Url))
url = 'http://quotes.money.163.com/service/chddata.html?code=0'+code+\
urllib.request.urlretrieve(url, filepath+code+'.csv')
##########################将股票数据存入数据库###########################
password = 'xxxx' #替换为自己的账户名和密码
db = pymysql.connect('localhost', name, password, charset='utf8')
sqlSentence1 = "create database stockDataBase"
cursor.execute(sqlSentence1)#选择使用当前数据库
sqlSentence2 = "use stockDataBase;"
fileList = os.listdir(filepath)
data = pd.read_csv(filepath+fileName, encoding="gbk")
#创建数据表,如果数据表已经存在,会跳过继续执行下面的步骤print('创建数据表stock_%s'% fileName[0:6])
收盘价 float, 最高价 float, 最低价 float, 开盘价 float, 前收盘 float, 涨跌额 float, \
涨跌幅 float, 换手率 float, 成交量 bigint, 成交金额 bigint, 总市值 bigint, 流通市值 bigint)"
print('正在存储stock_%s'% fileName[0:6])
成交量, 成交金额, 总市值, 流通市值) values ('%s',%s','%s',%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" % record
#获取的表中数据很乱,包含缺失值、Nnone、none等,插入数据库需要处理成空值
sqlSentence4 = sqlSentence4.replace('nan','null').replace('None','null').replace('none','null')
###########################查询刚才操作的成果##################################
db = pymysql.connect('localhost', name, password, 'stockDataBase')
cursor.execute('select * from stock_600000')