1 完整代码
import requests
import re
import pandas as pd
zl=int(input(
'''
请输入你要获取的数据类型id:
1 代表“资产负债表”
2 代表“利润表”
3 代表“现金流量表”
'''
))
if zl==1:
url='https://listxbrl.sse.com.cn/companyInfo/showBalance.do'
elif zl==2:
url='https://listxbrl.sse.com.cn/profit/showmap.do'
elif zl==3:
url='https://listxbrl.sse.com.cn/cash/showmap.do'
report_period=int(input(
'''
请输入你要获取的报告期id:
1 代表“季报”
2 代表“半年”
3 代表“三季度”
4 代表“年报”
'''
))
if report_period==1:
periodid='4000'
name='季报'
elif report_period==2:
periodid='1000'
name='半年'
elif report_period==3:
periodid='4400'
name='三季度'
elif report_period==4:
periodid='5000'
name='年报'
stockid=input('请输入6位数的股票代码:')
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
'Host':'listxbrl.sse.com.cn'
}
data={
'report_year': '2023',
'stock_id': stockid,
'report_period_id': periodid
}
response = requests.post(url, headers=headers, data=data)
response.json()
#提取域
field_list=[]
for i in range(response.json()['total']):
p=response.json()['columns'][0][i]['field']
field_list.append(p)
i=i+1
# field_list
#提取年份
title_list=[]
for i in range(response.json()['total']):
m=response.json()['columns'][0][i]['title']
title_list.append(m)
i=i+1
# title_list
#提取rows里面的数据
list_all=[]
for r in range(len(response.json()['rows'])):
list0=[]
for f in field_list:
#print(f)
n=response.json()['rows'][r][f]
list0.append(n)
list_all.append(list0)
r=r+1
# list_all
# 获取指标 静态数据
url1='https://listxbrl.sse.com.cn/companyInfo/toCompanyInfo.do?stock_id=600004.SS&report_year=2021&report_period_id=1000'
response1 = requests.get(url1, headers=headers)
response1 .encoding = response1.apparent_encoding
text=re.sub(r'\t|\n|\r','',response1 .text)
pattern = r"var name = \[ (.*?)\];.*?var mycolumns ="
matches = re.findall(pattern, text, re.DOTALL)
# 提取行索引指标
if zl==1:
index_list=matches[1].replace('"','').replace(' ','').split(',') #资产负债表指标
sheet='资产负债表'
elif zl==2:
index_list=matches[3].replace('"','').replace(' ','').split(',') #利润表指标
sheet='利润表'
elif zl==3:
index_list=matches[4].replace('"','').replace(' ','').split(',') #现金流量表指标
sheet='现金流量表'
print(f'*********你获取的是股票代码为“{stockid}”,报告类型为“{name}”,“{sheet}”的数据*********')
df=pd.DataFrame(list_all,columns=title_list)
df.set_index(pd.Index(index_list), inplace=True)
df.head()
2 补充内容
网上获取的数据是字符型,不能参与运算,所以需要转换为浮点型或者整数型
2.1 去掉千字符号
import re
# 定义一个函数来移除千位分隔符但保留小数点
def remove_thousands_separator(s):
return re.sub(r'[,]', '', s) # 使用正则表达式替换逗号和点号为空字符串
# 遍历DataFrame的列
for column in df.columns:
if df[column].dtype == object:
df[column] = df[column].astype(str).apply(remove_thousands_separator)
# 查看转换后的DataFrame
# df
2.2 转化为浮点型或者整数型
# 定义一个函数来进行类型转换
def convert_type(value):
# 如果值是字符串并且含有小数点,转换为浮点型
if isinstance(value, str) and '.' in value:
return float(value)
# 如果值是字符串并且等于'0',转换为整型
elif isinstance(value, str) and value == '0':
return int(value)
# 其他情况也返回整数型
return int(value)
# 应用函数到DataFrame的每一个元素
df = df.map(convert_type)
df.head()
3 保存
df.to_excel(f'{stockid}{name}{sheet}.xlsx')