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

如何使用BeautifulSoup提取HTML元素的data-score属性值?

解决提取HTML中data-score属性值的问题

你的代码没返回数据的原因很明确:soup.find_all("data-score")是在查找**标签名为<data-score>**的元素,但data-score是元素的属性,不是标签名,自然找不到任何结果。

修正方案

要提取带有data-score属性的元素,有两种常用方法:

方法1:使用attrs参数匹配属性

直接指定要查找的属性,只要元素包含该属性就会被匹配:

import requests
from bs4 import BeautifulSoup

response = requests.get("https://website")  # 补全正确的目标URL
soup = BeautifulSoup(response.text, "html.parser")

# 查找所有带有data-score属性的元素
result = soup.find_all(attrs={"data-score": True})

for item in result:
    # 提取属性值
    score = item.get("data-score")
    print(score)

方法2:使用CSS选择器(更简洁)

用CSS属性选择器[data-score]来定位元素:

import requests
from bs4 import BeautifulSoup

response = requests.get("https://website")
soup = BeautifulSoup(response.text, "html.parser")

# 使用CSS选择器匹配带data-score属性的元素
result = soup.select('[data-score]')

for item in result:
    # 直接通过字典方式获取属性值
    score = item["data-score"]
    print(score)

额外说明

  • 如果只需要提取data-score="100"的特定元素,可以把条件写得更精准:
    # 方法1:匹配属性值为100的元素
    result = soup.find_all(attrs={"data-score": "100"})
    # 方法2:CSS选择器精准匹配
    result = soup.select('[data-score="100"]')
    
  • 注意补全请求URL中的https://前缀,否则请求会失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:30:53