上市企业年报爬虫:
我的毕业论文要爬取 200 家军民融合上市企业连续 5 年的年报数据,需要收集企业名称和爬取年报数据,下面的爬虫代码是借鉴网友的,我稍微按照我的需要改动了一下就可以下载年报数据了,并且做了故障判断,下载过程不会中途停止,希望可以帮到急需数据的朋友。
主要思路:
- 自己在网站收集企业名称合成一个 excel 表
- 如图,我的 name.excel
- python 读取 name.excel 文件返回 company_set 企业名称集合(因为网上收集的数据由重复项,所有要用 set() 集合去重)
csv_file_path = 'D:\\temp2\\name.xlsx'
company_set = read_csv(csv_file_path)
- 下载文件到指定文件目录
for company in ['中利集团', '龙溪股份', '新光圆成', '轴研科技']:
os.makedirs('D:\\test\\PDF\\' + company)
g_orgId, g_plate, g_code = get_adress(company)
if g_orgId != '' and g_plate != '' and g_code != '':
get_PDF(g_orgId, g_plate, g_code)
print("下一家~")
- 完整代码:
import json
import os
from time import sleep
from urllib import parse
import xlrd
import requests
def get_adress(company_name):
url = "http://www.cninfo.com.cn/new/information/topSearch/detailOfQuery"
data = {
'keyWord': company_name,
'maxSecNum': 10,
'maxListNum': 5,
}
hd = {
'Host': 'www.cninfo.com.cn',
'Origin': 'http://www.cninfo.com.cn',
'Pragma': 'no-cache',
'Accept-Encoding': 'gzip,deflate',
'Connection': 'keep-alive',
'Content-Length': '70',
'User-Agent': 'Mozilla/5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 75.0.3770.100Safari / 537.36',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': 'application/json,text/plain,*/*',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
}
r = requests.post(url, headers=hd, data=data)
# print(r.text)
r = r.content
m = str(r, encoding="utf-8")
pk = json.loads(m)
orgI, plate, code = '', '', ''
if len(pk["keyBoardList"]) > 0:
orgI = pk["keyBoardList"][0]["orgId"] # 获取参数
plate = pk["keyBoardList"][0]["plate"]
code = pk["keyBoardList"][0]["code"]
# print(orgId, plate, code)
return orgI, plate, code
def download_PDF(url, file_name): # 下载pdf
url = url
r = requests.get(url)
f = open('D:\\test\\PDF\\' + company + "/" + file_name + ".pdf", "wb")
print('------> ', company)
f.write(r.content)
def get_PDF(orgI, plate, code):
url = "http://www.cninfo.com.cn/new/hisAnnouncement/query"
data = {
'stock': '{},{}'.format(code, orgI),
'tabName': 'fulltext',
'pageSize': 30,
'pageNum': 1,
'column': plate,
'category': 'category_ndbg_szsh;',
'plate': '',
'seDate': '',
'searchkey': '',
'secid': '',
'sortName': '',
'sortType': '',
'isHLtitle': 'true',
}
hd = {
'Host': 'www.cninfo.com.cn',
'Origin': 'http://www.cninfo.com.cn',
'Pragma': 'no-cache',
'Accept-Encoding': 'gzip,deflate',
'Connection': 'keep-alive',
# 'Content-Length': '216',
'User-Agent': 'User-Agent:Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': 'application/json,text/plain,*/*',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'X-Requested-With': 'XMLHttpRequest',
# 'Cookie': cookies
}
data = parse.urlencode(data)
# print(data)
r = requests.post(url, headers=hd, data=data)
# print(r.text)
r = str(r.content, encoding="utf-8")
r = json.loads(r)
reports_list = r['announcements']
# print(reports_list)
for report in reports_list:
print(report['announcementTitle'])
file_name = report['announcementTitle']
if file_name in ['2018年年度报告(更新后)','2017年年度报告(更新后)','2016年年度报告(更新后)','2015年年度报告(更新后)','2014年年度报告(更新后)','2018年年度报告', '2017年年度报告', '2016年年度报告', '2015年年度报告', '2014年年度报告']:
pdf_url = "http://static.cninfo.com.cn/" + report['adjunctUrl']
print("正在下载:" + pdf_url, "存放在当前目录:/" + company + "/" + file_name)
download_PDF(pdf_url, file_name)
sleep(2)
# 读取 csv 企业文件,去除 *ST 公司,返回公司名列表
def read_csv(path):
# 打开文件
data = xlrd.open_workbook(path)
# 通过文件名获得工作表,获取工作表1
table = data.sheet_by_name('Sheet1')
company_names = set()
# 我的 excel 有五列数据,所以要用5次 for
for name in list(table.col_values(0)):
if name[0] != '*' and name[0] != 'S':
company_names.add(name)
for name in list(table.col_values(1)):
if name[0] != '*' and name[0] != 'S':
company_names.add(name)
for name in list(table.col_values(2)):
if name[0] != '*' and name[0] != 'S':
company_names.add(name)
for name in list(table.col_values(3)):
if name[0] != '*' and name[0] != 'S':
company_names.add(name)
for name in list(table.col_values(4)):
if name[0] != '*' and name[0] != 'S':
company_names.add(name)
return company_names
if __name__ == '__main__':
# 从excel文件中获得企业名称集合
# csv_file_path = 'D:\\temp2\\name.xlsx'
# company_set = read_csv(csv_file_path)
# print(company_set)
# print(len(company_set))
# 主要代码
for company in ['中利集团', '龙溪股份', '新光圆成', '轴研科技']:
os.makedirs('D:\\test\\PDF\\' + company)
g_orgId, g_plate, g_code = get_adress(company)
if g_orgId != '' and g_plate != '' and g_code != '':
get_PDF(g_orgId, g_plate, g_code)
print("next one !!!")
print("all done !!!")
参考链接: https://blog.csdn.net/herr_kun/article/details/89707078#commentBox