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

Python抓取无class或id属性的HTML表格并转为DataFrame技术咨询

代码错误点梳理

  • 错误1:requests.get(body_class) 参数传入了类名字符串而非目标URL,请求逻辑完全错误
  • 错误2:requests.get(url, attrs={'class': body_class}) 用法错误,attrs是BeautifulSoup定位元素的参数,不属于requests库的请求参数
  • 错误3:直接将requests响应对象传入pd.read_html,该方法需要接收HTML文本或包含表格的HTML片段,而非请求响应对象

正确实现代码

from bs4 import BeautifulSoup
import requests
import pandas as pd

url = 'https://www.multistate.us/research/covid/public'
# 增加UA模拟浏览器请求,避免被反爬拦截
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
}
response = requests.get(url, headers=headers)
response.encoding = response.apparent_encoding
soup = BeautifulSoup(response.text, 'html.parser')

# 定位目标表格,可根据页面实际结构补充class、id等筛选条件
target_table = soup.find('table')

# 方案1:直接用pandas内置方法解析,无需手动遍历
df = pd.read_html(str(target_table))[0]
print(df)
print(f"表格尺寸(行数, 列数):{df.shape}")

# 方案2:手动遍历tr/td,适配格式特殊的表格,避免尺寸报错
rows = []
# 提取表头
header = [th.get_text(strip=True) for th in target_table.find('tr').find_all('th')]
# 遍历数据行
for tr in target_table.find_all('tr')[1:]:
    row_data = [td.get_text(strip=True) for td in tr.find_all('td')]
    # 过滤列数不匹配的异常行,解决尺寸报错问题
    if len(row_data) == len(header):
        rows.append(row_data)
df = pd.DataFrame(rows, columns=header)
print(df)
print(f"表格尺寸(行数, 列数):{df.shape}")

尺寸错误处理说明

手动遍历触发尺寸错误的核心原因是存在列数和表头不匹配的异常行(空行、跨列合并行、末尾统计行等),上述代码中增加了列数一致性判断即可解决问题。如果需要保留跨列合并的单元格数据,可额外读取td的colspan属性对缺失列做补位处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 19:09:02