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

使用BeautifulSoup提取<td>文本报错,如何获取目标数字或最大值?

问题:BeautifulSoup提取标签文本报错

原代码:

url = "C:\\local.html"
page = open(url)
soup = BeautifulSoup(page.read(), "html.parser")
NoFall = soup.find_all("div", {"id":"Kendo_Table1535711951642"})
for AuxCopy in NoFall:
    product = AuxCopy.find('table').find_all('tr')
    for tr in product:
        td = tr.find_all('td', {"data-label":"Fallen Behind Days"})
        print(td)

代码输出:

[]
[]
[<td class="ng-binding ng-scope nowrap" data-colid="FallenBehindDays" data-label="Fallen Behind Days" title="1">1</td>]
[<td class="ng-binding ng-scope nowrap" data-colid="FallenBehindDays" data-label="Fallen Behind Days" title="0">0</td>]
[<td class="ng-binding ng-scope nowrap" data-colid="FallenBehindDays" data-label="Fallen Behind Days" title="6">6</td>]
[<td class="ng-binding ng-scope nowrap" data-colid="FallenBehindDays" data-label="Fallen Behind Days" title="1">1</td>]

尝试用td.text提取数字时,出现错误:

AttributeError: ResultSet object has no attribute 'text'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?

需求:提取出td内的数字(1、0、6、1),或找出其中的最大值。


解决方法

错误原因

find_all()返回的是元素列表(ResultSet),列表本身没有.text属性,必须针对列表内的单个元素调用该属性。而每个<tr>里仅存在一个符合data-label="Fallen Behind Days"的<td>,因此更适合用find()直接获取单个元素。

1. 提取所有数字

修改代码,用find()替代find_all(),并跳过无匹配的行:

url = "C:\\local.html"
page = open(url)
soup = BeautifulSoup(page.read(), "html.parser")
NoFall = soup.find_all("div", {"id":"Kendo_Table1535711951642"})
for AuxCopy in NoFall:
    product = AuxCopy.find('table').find_all('tr')
    for tr in product:
        td = tr.find('td', {"data-label":"Fallen Behind Days"})
        if td:
            print(td.text.strip())

输出结果:

1
0
6
1

2. 找出最大值

提取数字并转为整数,存入列表后取最大值:

url = "C:\\local.html"
page = open(url)
soup = BeautifulSoup(page.read(), "html.parser")
NoFall = soup.find_all("div", {"id":"Kendo_Table1535711951642"})
days_list = []
for AuxCopy in NoFall:
    product = AuxCopy.find('table').find_all('tr')
    for tr in product:
        td = tr.find('td', {"data-label":"Fallen Behind Days"})
        if td:
            day = int(td.text.strip())
            days_list.append(day)
if days_list:
    print("最大值:", max(days_list))
else:
    print("未找到有效数据")

输出结果:

最大值: 6

内容的提问来源于stack exchange,提问作者Iván Magaña

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:05:13