#!/usr/bin/env python2#-*-coding:utf-8-*-
'''@version: python2.7
@author: ‘zyjsuper‘
@license: Apache Licence
@software: PyCharm
@file: gettodb.py
@time: $2019-10-03 10:01'''
#导入需要使用到的模块
importurllibimportreimportpandas as pdimportpymysqlimportos#爬虫抓取网页函数
defgetHtml(url):
html=urllib.request.urlopen(url).read()
html= html.decode('utf-8')returnhtml#抓取网页股票代码函数
defgetStackCode(html):
s= r'
'pat=re.compile(s)code=pat.findall(html)returncode#########################开始干活############################
Url = 'http://quote.eastmoney.com/stocklist.html' #东方财富网股票数据连接地址
filepath = '/Users/zyjsuper/Documents/data' #定义数据文件保存路径#实施抓取
code =getStackCode(getHtml(Url))#获取所有股票代码(以6开头的,应该是沪市数据)集合
CodeList =[]for item incode:if item[0] == '6':
CodeList.append(item)#抓取数据并保存到本地csv文件
for code inCodeList:print('正在获取股票%s数据' %code)
name = 'cipuser'password= 'cippass' #替换为自己的账户名和密码#建立本地数据库连接(需要先开启数据库服务)
db = pymysql.connect('192.168.128.130', name, password, charset='utf8')
cursor=db.cursor()#创建数据库stockDataBase
#sqlSentence1 = "create database stockDataBase"#cursor.execute(sqlSentence1) # 选择使用当前数据库
sqlSentence2 = "use stockDataBase;"cursor.execute(sqlSentence2)#获取本地文件列表
fileName = ''data= ''fileList=os.listdir(filepath)#依次对每个数据文件进行存储
收盘价 float, 最高价 float, 最低价 float, 开盘价 float, 前收盘 float, 涨跌额 float, \
print('正在存储stock_%s' % fileName[0:6])
length=len(data)for i inrange(0, length):
record=tuple(data.loc[i])#插入数据语句
sqlSentence4 = sqlSentence4.replace('nan', 'null').replace('None', 'null').replace('none', 'null')
cursor.execute(sqlSentence4)except:#如果以上插入过程出错,跳过这条数据记录,继续往下进行
db.close()###########################查询刚才操作的成果##################################
db = pymysql.connect('192.168.128.130', name, password, 'stockDataBase')
cursor.execute('select * from stock_600000')
results=cursor.fetchall()for row inresults:print(row)#关闭