You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pandas.read_html和BeautifulSoup无法获取网页全部表格如何解决

问题根因

Pro Football Reference 所属的Sports Reference系列站点,静态HTML中仅前2个统计表格为直接渲染的DOM节点,其余所有表格均被包裹在HTML注释标签<!-- -->内部。pandas.read_html、默认配置的BeautifulSoup均不会解析注释节点内的元素,因此仅能识别到2个表格,该现象和前端JS渲染无关。

实现方案

方案1:BeautifulSoup提取注释节点解析

核心逻辑是单独提取页面内所有注释内容,筛选出包含表格的片段后二次解析,合并所有表格后按索引取目标数据即可。

import requests
import pandas as pd
from bs4 import BeautifulSoup, Comment

url = 'https://www.pro-football-reference.com/years/2021/'
# 添加合法User-Agent避免被反爬拦截
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
}
resp = requests.get(url, headers=headers)
soup = BeautifulSoup(resp.content, 'html.parser')

all_tables = []
# 先收集直接渲染的表格
for direct_table in soup.find_all('table', class_='stats_table'):
    all_tables.append(pd.read_html(str(direct_table))[0])

# 再收集注释内的表格
for comment_node in soup.find_all(string=lambda x: isinstance(x, Comment)):
    if 'class="sortable stats_table"' in comment_node:
        comment_soup = BeautifulSoup(comment_node, 'html.parser')
        hidden_table = comment_soup.find('table', class_='stats_table')
        if hidden_table:
            all_tables.append(pd.read_html(str(hidden_table))[0])

# 校验表格总数
print(f"共解析到{len(all_tables)}个表格")
# 索引从0开始,第3个表格对应索引2,第6个表格对应索引5
table_3 = all_tables[2]
table_6 = all_tables[5]

方案2:预处理源码后直接用pandas.read_html

直接替换掉页面源码中的注释起止标记,让被注释包裹的表格变为普通DOM节点,即可一次性被pandas.read_html识别,代码更简洁:

import requests
import pandas as pd

url = 'https://www.pro-football-reference.com/years/2021/'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
}
resp = requests.get(url, headers=headers)
# 移除注释标签
processed_html = resp.text.replace('<!--', '').replace('-->', '')
all_tables = pd.read_html(processed_html)

print(f"共解析到{len(all_tables)}个表格")
table_3 = all_tables[2]
table_6 = all_tables[5]

提示:爬取该站点时请控制请求频率,遵守站点的robots协议规则。

内容的提问来源于stack exchange,提问作者jakecm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 01:36:28