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

如何抓取HTML元素中data-sort属性的英寸身高数据?

问题描述

我正在抓取多名在册运动员的身高数据,已编写相关代码,但检查元素后发现,class为height的<td>标签文本内容是英尺格式身高(如6-7),而其data-sort属性中存储的是英寸格式的数值(如79)。目前使用get_text()或.text方法仅能获取英尺数据,无法提取英寸数据,希望获取英寸数据以便进行数值计算。

示例HTML

<td class="height" data-sort="79">6-7</td>
<td class="height" data-sort="85">7-1</td>
<td class="height" data-sort="74">6-2</td>

现有代码

#This is my code

from bs4 import BeautifulSoup
import requests 

urls=['https://goduke.com/sports/mens-basketball/roster']

ListData=[]
for x in range(len(urls)):
    page=requests.get(urls[x]).text
    pagesoup=BeautifulSoup(page,'html.parser')
    h=pagesoup.find_all('td', class_="height")
    ListData.append(h)
NewList=[]
for b in range(len(ListData)):
    new=[]
    for x in ListData[b]:
        print(x.text)
解决方案

要提取data-sort属性中的英寸数值,在BeautifulSoup中可以通过标签对象的get()方法直接获取属性值,还可以将其转换为整数类型方便后续数值计算。修改后的代码如下:

from bs4 import BeautifulSoup
import requests 

urls=['https://goduke.com/sports/mens-basketball/roster']

ListData=[]
for url in urls:
    page=requests.get(url).text
    pagesoup=BeautifulSoup(page,'html.parser')
    height_tags=pagesoup.find_all('td', class_="height")
    ListData.append(height_tags)

# 提取data-sort属性的数值并存储
NewList=[]
for tag_group in ListData:
    heights_in_inches=[]
    for tag in tag_group:
        # 获取data-sort属性值并转为整数
        inch_height=int(tag.get('data-sort'))
        heights_in_inches.append(inch_height)
        print(f"英尺格式: {tag.text}, 英寸数值: {inch_height}")
    NewList.append(heights_in_inches)

# 后续可直接用NewList中的数值进行计算
print("所有运动员英寸身高列表:", NewList)

关键说明

  • 使用tag.get('data-sort')获取属性值更安全,避免属性不存在时抛出异常;若确定属性必然存在,也可直接用tag['data-sort']。
  • 将字符串类型的属性值转为int后,即可直接开展数值计算(如求平均身高、身高排序等)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 08:56:06