有大佬可以帮忙看看吗?我用这个代码为什么爬不出来东方财富网中的神州数码(000034)股票的信息。
一、Python爬虫抓取网页数据并保存到本地数据文件中
首先导入需要的数据模块,定义函数:
#导入需要使用到的模块
import urllib
import re
import pandas as pd
import pymysql
import os
#爬虫抓取网页函数
def getHtml(url):
html = urllib.request.urlopen(url).read()
html = html.decode('utf8')
return html
#抓取网页股票代码函数
def getStackCode(html):
s = r'获取代码并保存:
Url = r'http://data.eastmoney.com/zjlx/000034.html'#神州数码股票数据连接地址
filepath = 'F:\data\'#定义数据文件保存路径
#实施抓取
code = getStackCode(getHtml(Url))
CodeList = []
#抓取数据并保存到本地csv文件
for code in CodeList:
print('正在获取股票%s数据'%code)
url = 'http://quotes.money.163.com/service/chddata.html?code=0'+code+
'&end=20161231&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP'
urllib.request.urlretrieve(url, filepath+code+'.csv')
二、将数据存储到MySQL数据库
首先建立本地数据库连接:
#建立本地数据库连接(需要先开启数据库服务) db = pymysql.connect(host='localhost', user = 'root', password = '941207', port=3306,charset='utf8') cursor = db.cursor()
其中,数据库名称(name)和密码(password)是安装MySQL时设置的。
创建数据库,专门用来存储本次股票数据:
#创建数据库stockDatabase,如果存在则跳过 sqlSentence1 = "create database if not exists stockDatabase" cursor.execute(sqlSentence1)#选择使用当前数据库 sqlSentence2 = "use stockDatabase;" cursor.execute(sqlSentence2)
在首次运行的时候一般都会正常创建数据库,但如果再次运行,因数据库已经存在,那么跳过创建,继续往下执行。创建好数据库后,选择使用刚刚创建的数据库,在该数据库中存储数据表。
具体的存储代码:
#获取本地文件列
fileList = os.listdir(filepath)
#依次对每个数据文件进行存储
for fileName in fileList:
data = pd.read_csv(filepath+fileName, encoding="utf8")
#创建数据表,如果数据表已经存在,会跳过继续执行下面的步骤print('创建数据表stock_%s')
sqlSentence3 = "create table if not exists stock_%s" + "(日期 date, 股票代码 VARCHAr(10), 名称 VARCHAr(10), 收盘价 float,
最高价 float, 最低价 float, 开盘价 float, 前收盘 float, 涨跌额 float, 涨跌幅 float, 换手率 float,
成交量 bigint, 成交金额 bigint, 总市值 bigint, 流通市值 bigint)"
cursor.execute(sqlSentence3)#迭代读取表中每行数据,依次存储(整表存储还没尝试过)
print('正在存储stock_%s')
length = len(data)
for i in range(0, length):
record = tuple(data.loc[i])
#插入数据语句
try:
sqlSentence4 = "insert into stock_%s" + "(日期, 股票代码, 名称, 收盘价, 最高价, 最低价, 开盘价,
前收盘, 涨跌额, 涨跌幅, 换手率, 成交量, 成交金额, 总市值, 流通市值)
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')
cursor.execute(sqlSentence4)
except:#如果以上插入过程出错,跳过这条数据记录,继续往下进行
break
完成MySQL数据库数据存储后,需要关闭数据库连接:
#关闭游标,提交,关闭数据库连接 cursor.close() db.commit() db.close()
三、MySQL数据库查询
#重新建立数据库连接
db = pymysql.connect(host='localhost', user = 'root', password = '941207',database='stockDatabase', port=3306,charset='utf8')
cursor = db.cursor()
#查询数据库并打印内容
cursor.execute('select * from stock_000034')
results = cursor.fetchall()
for row in results:
print(row)
#关闭
cursor.close()
db.commit()
db.close()



