python爬取价值大师线:中证指数成份股的价值大师评估信息

您可以参考《爬取价值大师线:使用 Python 获取股票估值比率数据》一文中的代码说明,因为本文只是在原有代码的基础上添加了获取指数成分股代码的自定义函数,内容与上一篇文章相似。

需要注意的是,本文仅支持中证指数,不支持其他机构指数,比如不支持国证指数,因为自定义函数是基于中证指数的数据进行调取的。

若想获取该指数成分股的价值大师以及相关评估信息,只需在自定义函数中增加中证指数的代码即可。

代码

import akshare as ak
import requests
import re
from bs4 import BeautifulSoup
import pandas as pd

# 获取中证指数成份股代码

def get_component_codes(symbol):

    index_stock_cons_csindex = ak.index_stock_cons_csindex(symbol=symbol)

    codes = index_stock_cons_csindex['成分券代码']

    return codes

  

# 通过代码,获取价值大师的价值线

def get_valuation_ratios(code):

    url = f'https://www.gurufocus.cn/stock/{code}/term/gf_value'

    response = requests.get(url)

    soup = BeautifulSoup(response.content, 'html.parser')


    # 获取大师价值线

    element_jzx = soup.select_one('#term-page-title').text.strip()

    element_jzx = re.findall("\d+\.\d+", element_jzx)[0]


    # 获取名称

    element_mc = soup.select_one('html body div div main div:nth-child(1) div:nth-child(2) div:nth-child(1) div:nth-child(1) div:nth-child(2) div:nth-child(1) h1 span:nth-child(1)').text.strip()

    # 获取现价

    element_xj = soup.select_one('html body div div main div:nth-child(1) div:nth-child(2) div:nth-child(1) div:nth-child(1) div:nth-child(2) div:nth-child(2)')

    element_xj.span.decompose()  # 去掉span标签

    element_xj = re.findall(r'\d+\.\d+', element_xj.text.strip())[0]  # 只保留数字和小数点

    # 拼接链接

    link = f'https://www.gurufocus.cn/stock/{code}/summary'


    # 创建一个pandas DataFrame来保存比率

    ratios = pd.DataFrame({

        '代码': [f'=HYPERLINK("{link}", "{code}")'],

        '名称': [element_mc],

        '大师价值': [element_jzx],

        '现价': [element_xj],

    })

  

    # 将“代码”列设置为索引

    ratios = ratios.set_index('代码')

    return ratios

  
# 用中指指数成份股获取价值大师价格

def get_all_valuation_ratios(index_code):       # 参数为中证指数代码

    codes = get_component_codes(index_code)         # 调取自定义函数——获取中证指数的代码列

    all_ratios = pd.DataFrame()      # 创建一个pandas DataFrame来保存所有的比率数据

    for code in codes:      # 遍历所有代码并获取比率数据

        ratios = get_valuation_ratios(code)     # 调取自定义函数——获取价值大师的方法

        all_ratios = pd.concat([all_ratios, ratios])    # 将遍历的数据进行拼接

    return all_ratios

get_all_valuation_ratios('000016').to_csv(f'指数成分股价值大师.csv', index=True, encoding='utf-8-sig')
  1. 使用 Python 获取股票估值比率数据
  2. 获取中证指数成份股代码的自定义函数
  3. 中证指数成份股的价值大师评估信息获取方法
  4. 通过代码获取股票的价值大师
  5. 投资者必看:中证指数成份股的价值大师评估信息

#金融 #投资 #数据分析 #Python编程 #股票分析

THE END