使用Python爬取东方财富网的上证A股数据
import requests
import xlsxwriter
import time
def creatlist(item):
temp = []
temp.append(item['f14'])#股票名称
temp.append(int(item['f12']))#股票代码
temp.append(item['f2']) #最新价
temp.append(item['f3'] if item['f3'] == '-' else str(item['f3'])+"%")#跌涨幅
temp.append(item['f4'])#跌涨额
temp.append(item['f5']) #成交量
temp.append(item['f6']) #成交额
temp.append(item['f7'] if item['f7'] == '-' else str(item['f7'])+"%")#振幅
temp.append(item['f8'] if item['f8'] == '-' else str(item['f8'])+"%")#换手率
temp.append(item['f9'])#市盈率
temp.append(item['f10']) #量比
temp.append(item['f15'])#最高
temp.append(item['f16'])#最低
temp.append(item['f17'])#今开
temp.append(item['f18'])#昨收
return temp
try:
abc = "http://10.push2.eastmoney.com/api/qt/clist/get?pn=1&pz=20&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=m:1+t:2,m:1+t:23&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152"
sum = requests.get(abc).json()['data']['total']
url = "http://10.push2.eastmoney.com/api/qt/clist/get?pn=1&pz="+ str(sum) +"&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=m:1+t:2,m:1+t:23&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152"
res = requests.get(url).json()['data']['diff']
timenow = time.strftime("%Y%m%d%H%M%S", time.localtime())
workbook = xlsxwriter.Workbook("shangzhengstockexchange" + timenow + ".xlsx")
worksheet = workbook.add_worksheet()
namelist = ['股票名称', '股票代码', '最新价','跌涨幅','跌涨额','成交量','成交额','振幅','换手率','市盈率','量比','最高','最低','今开','昨收']
worksheet.write_row(0, 0, namelist)
i = 1
for item in res:
my_list = creatlist(item)
worksheet.write_row(i, 0, my_list)
i = i + 1
workbook.close()
except Exception as e:
print(e)
finally:
print("Program end!")
结果如下图所示
python上证.png