准备工作:
1、安装Python解释器,详见“http://u6.gg/sS48u”。安装requests、pandas、xlrd这些Python依赖包。具体方法如下,按Win R,调出命令行窗口(黑窗口),在其中输入pip install xxx(xxx代表pandas等依赖包)。
2、复制代码到本地文件记事本中,然后将.txt后缀改为.py。
3、在Excel表中的第一个sheet中添加下面数据,“公司名称”(要求为证券简称)和“时间范围”(可为单年、连续多年、跨年),具体示例如下:
示例文档模板
4、双击.py文件。
抓取年报示例动画如下:
运行代码:
_version__ = 20200406
# 读取Excel表格中的数据,开始获取年报
# 读取的Excel表格有一定的格式
# 可以获取该公司当年、跨年、连续年的年报
import requests
import json
import pandas as pd
import os
def deal_year(year):
"""
接收一个字符串,转变为列表形式的数据。
:param year: 字符串,其中可以包含、-
:return: 返回年份组成的列表
"""
if "、" in year and "-" in year: # 处理时间范围中有连续的时间和单个时间
year_list = year.split("、")
year_list = [year_list list(range(int(y.split(-)[0]), int(y.split(-)[1]) 1)) for y in year_list if "-" in y][0]
year_list = [str(y) for y in year_list if "-" not in str(y)]
elif "、" in year: # 处理时间范围中不连续的部分
year_list = [str(y) for y in year.split("、")]
elif "-" in year: # 处理时间范围中连续部分
year_list = list(range(int(year.split("-")[0]), int(year.split("-")[1]) 1))
else: # 处理单个年的部分
year_list = [year]
return year_list
def send_requests(key_words):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36"}
url = "http://www.cninfo.com.cn/new/fulltextSearch/full?searchkey={}&sdate=&edate=&isfulltext=false&sortName=pubdate&sortType=desc&pageNum=1".format(
key_words)
response = requests.get(url, headers=headers)
response = response.content.decode()
dict_data = json.loads(response) # 请求每个页面的数据
if not os.path.exists("download"):
os.mkdir("download")
for value_dict in dict_data["announcements"]:
name = value_dict["announcementTitle"] # 该页面上的文件名称
url_son = value_dict["adjunctUrl"] # pdf文件的链接
path = r".download" name.replace("<em>", "").replace("</em>", "") ".pdf"
if "年度报告" in path and "半年度报告" not in path and "摘要" not in path and "财务" not in path:
url_pdf = "http://static.cninfo.com.cn/" url_son
response = requests.get(url_pdf, headers=headers)
response = response.content
with open(path, "wb ") as f:
f.write(response)
break
df = pd.read_excel("./获取公司年报清单.xlsx")
for name, year in zip(df["公司名称"], df["时间范围"]):
# print(name)
name = str(name).strip() # 处理公司名称中不规范的空格
year = str(year)
year_list = deal_year(year) # 处理时间范围
for year in year_list:
key_words = name str(year) "年报"
send_requests(key_words)
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至123456@qq.com 举报,一经查实,本站将立刻删除。