上篇文章提到四行代码获取股票历史数据,有人说不能用了,所以就写了本代码验证。
一、基本思路
这段代码是获取以6开头的股票数据,大家可以根据自己的需要来改写。
基本思路就是在网上(url='http://quote.eastmoney.com/stock_list.html')来获取所有的股票代码,存放在daima 列表中,循环列表依此取出数据,有些股票是没有数据的,做了异常处理。
二、完整代码
#!/usr/bin/python# # Created by 老刘 on 2020/5/12# # Author: Lao Liu <412842374@qq.com>#
import requests,re
import tushare as ts
#获取股票代码网址
url='http://quote.eastmoney.com/stock_list.html'
headers={
'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36',
}
#发出请求
response=requests.get(url,headers = headers)
#设置编码
response.encoding='gb2312'html=response.text
#利用正则取出股票名称和代码存放在lists列表中
pat=' <li><a target="_blank".*?">(.*?)</a></li>'
lists=re.findall(pat,html,re.S)
#循环列表
for list in lists:
#把股票名称存放在name列表里
name = list
#把代码存在daima列表里
daima = list[-8:].replace("(", '').replace(")", '')
#如果以6开头,*载下**数据
if daima[0] == '6':
try:
print("正在*载下**%s的数据"%list)
ata=ts.get_hist_data(daima)
data.to_csv('./股票数据/%s.csv'%list,index=False)
print("%s的数据*载下**完毕"%list)
except:
print("%s的数据*载下**失败!********************" % list)
*载下**到本地的文件。

打开后的数据

最近在学pandas,有兴趣的可以交流