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

如何用Python的BeautifulSoup遍历HTML所有tr标签获取完整数据

解决KenPom数据爬取不完整的问题

问题核心在于KenPom的评分表格采用了多组<thead>+<tbody>的分段结构,而非单个<tbody>包含所有数据行,所以原代码中soup.find('tbody')仅能获取第一个分段的数据。以下是两种可靠的修改方案:

方案1:直接提取所有数据行

跳过分段的<tbody>,直接定位表格内所有非表头的<tr>标签:

from bs4 import BeautifulSoup
import requests

# 模拟浏览器请求,避免反爬拦截
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}

url = "https://kenpom.com"
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')

# 定位到评分表格(通过ID精准匹配)
ratings_table = soup.find('table', id='ratings-table')
# 获取表格内所有<tr>,再过滤出包含<td>的行(排除表头行)
data_rows = [row for row in ratings_table.find_all('tr') if row.find('td')]

# 遍历处理所有数据行
for row in data_rows:
    cells = row.find_all('td')
    # 示例提取球队名称(根据实际列索引调整)
    team = cells[1].get_text(strip=True)
    # 提取其他字段(比如效率值、排名等)
    # adj_em = cells[2].get_text(strip=True)
    print(team)

方案2:遍历所有<tbody>分段

既然数据被拆分到多个<tbody>中,直接遍历所有<tbody>并收集其中的<tr>:

from bs4 import BeautifulSoup
import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}

url = "https://kenpom.com"
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')

# 获取页面中所有的<tbody>标签
all_tbodies = soup.find_all('tbody')
all_data_rows = []

# 遍历每个<tbody>,收集其中的<tr>
for tbody in all_tbodies:
    rows = tbody.find_all('tr')
    all_data_rows.extend(rows)

# 处理数据行
for row in all_data_rows:
    cells = row.find_all('td')
    if cells:
        team = cells[1].get_text(strip=True)
        print(team)

关键说明

  • 两种方案都能覆盖所有362条数据,方案1更直接,方案2更贴合页面结构;
  • 务必添加User-Agent请求头,否则KenPom的反爬机制会拦截请求,返回空页面或错误;
  • 列索引(比如cells[1])需要根据页面实际HTML结构调整,可通过浏览器开发者工具查看具体列位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 22:52:37