1. 对东方财富官网的分析
步骤:
- 通过刷新网页,点击等操作,我们发现https://datacenter-web.eastmoney.com/api/data/v1/get?请求后面带着一些参数即可以获取到相应数据。
- 我们使用python来模拟这个请求即可。
我们以如下选择的页面为切入点,以此获取当前所有A股的一些基本数据。
通过F12调出浏览器调试框,对该网站的数据拉取协议为参考,然后通过python模拟此类请求,进行获取数据,如下图所示:
主要代码如下:
import pandas as pd
from typing import List
import requests, json
class CustomedSession(requests.Session):
def request(self, *args, **kwargs):
kwargs.setdefault('timeout', 60)
return super(CustomedSession, self).request(*args, **kwargs)
MAX_CONNECTIONS = 50
session = CustomedSession()
adapter = requests.adapters.HTTPAdapter(pool_connections = MAX_CONNECTIONS,
pool_maxsize = MAX_CONNECTIONS,
max_retries = 5)
session.mount('http://', adapter)
session.mount('https://', adapter)
# 请求地址
QEURY_URL = 'http://datacenter-web.eastmoney.com/api/data/v1/get'
# HTTP 请求头
EASTMONEY_REQUEST_HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko',
'Accept': '*/*',
'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
# 'Referer': 'http://quote.eastmoney.com/center/gridlist.html',
}
# 请求返回值过滤
RESULT_FIELDS = {
'SECURITY_CODE': '股票代码',
'SECURITY_NAME_ABBR': '股票名称',
'END_DATE': '本次股东户数统计截止日',
'PRE_END_DATE': '上次股东户数统计截止日',
'INTERVAL_CHRATE': '区间涨跌幅',
'AVG_MARKET_CAP': '户均持股市值',
'AVG_HOLD_NUM': '户均持股数量',
'TOTAL_MARKET_CAP': '总市值',
'TOTAL_A_SHARES': '总股本',
'HOLD_NOTICE_DATE': '公告日期',
'HOLDER_NUM': '本次股东户数',
'PRE_HOLDER_NUM': '上次股东户数',
'HOLDER_NUM_CHANGE': '股东户数增减',
'HOLDER_NUM_RATIO': '股东户数较上期变化百分比',
'f2': '最新价',
'f3': '涨跌幅百分比',
}
# 请求页码
QEURY_PAGE = 1
# 请求参数
QUERY_PARAM = [
('sortColumns', 'HOLD_NOTICE_DATE,SECURITY_CODE'),
('sortTypes', '-1,-1'),
('pageSize', 500),
('pageNumber', QEURY_PAGE),
('columns', 'SECURITY_CODE,SECURITY_NAME_ABBR,END_DATE,INTERVAL_CHRATE,AVG_MARKET_CAP,AVG_HOLD_NUM,TOTAL_MARKET_CAP,TOTAL_A_SHARES,HOLD_NOTICE_DATE,HOLDER_NUM,PRE_HOLDER_NUM,HOLDER_NUM_CHANGE,HOLDER_NUM_RATIO,END_DATE,PRE_END_DATE',),
('quoteColumns', 'f2,f3'),
('source', 'WEB'),
('client', 'WEB'),
('reportName', 'RPT_HOLDERNUMLATEST'),
]
"""
获取沪深A股市场最新公开的股东数目变化情况: 当作获取所有股票
Parameters
None
Returns
DataFrame
"""
def get_latest_holder_number() -> pd.DataFrame:
global QEURY_PAGE
QEURY_PAGE = 1
PAGE_COUNT = 100
dfs: List[pd.DataFrame] = []
while 1:
if QEURY_PAGE > PAGE_COUNT:
break
params = tuple(QUERY_PARAM)
response = session.get(QEURY_URL, headers=EASTMONEY_REQUEST_HEADERS, params=params)
resultJson = response.json()
PAGE_COUNT = resultJson.get('result').get('pages')
if PAGE_COUNT is None:
break
data = resultJson.get('result').get('data')
if data is None:
break
df = pd.DataFrame(data)
df = df.rename(columns=RESULT_FIELDS)[RESULT_FIELDS.values()]
dfs.append(df)
QEURY_PAGE += 1
if len(dfs) == 0:
df = pd.DataFrame(columns=RESULT_FIELDS.values())
return df
df = pd.concat(dfs, ignore_index=True)
return df
if __name__ == "__main__":
data = get_latest_holder_number()
print(data)
调用如上函数即可:
更多内容:【爬虫】爬取A股数据系列