如何用BeautifulSoup访问Marketscreener估值表格特定数据(如2024年P/E ratio)
解决方案:抓取Marketscreener估值板块第一个表格的特定数据
问题说明
需要从Marketscreener网站的「估值」板块下第一个表格中,提取特定条目(例如2024年的市盈率P/E ratio),但当前代码会遍历并打印所有表格数据,无法精准定位目标内容。
当前代码(中文翻译版)
import requests from bs4 import BeautifulSoup url = 'https://www.marketscreener.com/quote/stock/MICROSOFT-CORPORATION-4835/financials/' soup = BeautifulSoup(requests.get(url).content, 'html.parser') # 遍历所有匹配的表格 for table in soup.select('table.BordCollapseYear2'): # 遍历表格每一行 for tr in table.select('tr'): row = [td.get_text(strip=True, separator=' ') for td in tr.select('td')] print(row)
当前输出(中文翻译版,关键片段)
['财年周期: 1月', '2020', '2021', '2022', '2023', '2024', '2025'] ['市值 1', '12 986', '47 749', '41 428', '26 353', '-', '-'] ['企业价值(EV) 1', '12 074', '46 568', '40 171', '24 444', '23 585', '22 437'] ['市盈率(P/E ratio)', '-63,6x', '-502x', '-175x', '-148x', '-194x', '-735x'] ...
修改后的代码(精准抓取目标数据)
import requests from bs4 import BeautifulSoup url = 'https://www.marketscreener.com/quote/stock/MICROSOFT-CORPORATION-4835/financials/' soup = BeautifulSoup(requests.get(url).content, 'html.parser') # 获取第一个估值表格(只取第一个匹配的表格) valuation_table = soup.select_one('table.BordCollapseYear2') if not valuation_table: print("未找到目标表格") exit() # 提取表头行,确定年份对应的索引 target_year = '2024' year_index = -1 pe_ratio_value = None # 遍历表格所有行 for tr in valuation_table.select('tr'): row = [td.get_text(strip=True, separator=' ') for td in tr.select('td')] if not row: continue # 识别表头行(包含财年周期和年份) if row[0].startswith('财年周期'): if target_year in row: year_index = row.index(target_year) continue # 找到市盈率(P/E ratio)行 if row[0] == '市盈率(P/E ratio)': if year_index != -1 and len(row) > year_index: pe_ratio_value = row[year_index] break # 输出结果 if pe_ratio_value: print(f"2024年的市盈率(P/E ratio)为: {pe_ratio_value}") else: print("未找到2024年的市盈率数据")
代码说明
- 定位第一个表格:使用
select_one代替select,直接获取页面中第一个BordCollapseYear2类的表格,也就是估值板块的目标表格。 - 确定年份索引:先找到表头行,定位2024年在列表中的位置,后续用这个索引提取对应列的数据。
- 抓取目标行数据:遍历行时匹配「市盈率(P/E ratio)」的行,再用年份索引取出对应年份的数据。
内容的提问来源于stack exchange,提问作者Gustaf
相关产品推荐
相关产品推荐

