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

如何使用BeautifulSoup选取网页中同一class下多个表格里的目标表格

问题排查与修复

错误原因

  • 查找表格的方法使用错误:soup.find('table') 只会返回页面中第一个<table>标签的对象,而非所有表格的集合,后续对单个对象做遍历、索引访问操作都会触发报错。
  • 缺少变量初始化逻辑:如果循环遍历中未匹配到目标表格,直接调用table_index会抛出变量未定义的异常。
  • 可选优化:原请求未携带浏览器标识,容易被站点反爬策略拦截,返回异常页面导致无法定位到目标表格。

修复后代码

import requests
from bs4 import BeautifulSoup

url = "https://www.macrotrends.net/stocks/charts/TSLA/tesla/revenue"
# 模拟浏览器请求头,避免反爬拦截
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"
}
data = requests.get(url, headers=headers).text 
soup = BeautifulSoup(data, "html5lib")
# 用find_all获取所有匹配指定class的表格,返回列表格式
tables = soup.find_all('table', class_="historical_data_table table")

table_index = None
for index, table in enumerate(tables):
    if "Tesla Quarterly Revenue" in str(table):
        table_index = index
        break

if table_index is not None:
    print(tables[table_index].prettify())
else:
    print("未匹配到目标表格")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 14:06:00