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

如何在BeautifulSoup中使用data-testid参数提取HTML指定内容?

用BeautifulSoup通过data-testid提取数值的方法

针对你给出的HTML片段,想要用data-testid代替class来提取数值39,BeautifulSoup有两种简单的实现方式:

方法一:用转义后的关键字参数

因为Python变量名不能包含横杠,所以把data-testid转写成data_testid,直接作为find方法的关键字参数传入:

from bs4 import BeautifulSoup

html = '<div data-testid="hero-rating-bar__popularity__score" class="sc-edc76a2-1 gopMqI">39</div>'
soup = BeautifulSoup(html, 'html.parser')

# 查找目标元素
target_elem = soup.find(data_testid="hero-rating-bar__popularity__score")
# 提取并清理文本内容
if target_elem:
    popularity_score = target_elem.get_text(strip=True)
    print(popularity_score)  # 输出:39

方法二:用attrs字典指定属性

直接通过attrs字典传入原始的属性名和对应值,适合属性名包含特殊字符的场景:

target_elem = soup.find(attrs={"data-testid": "hero-rating-bar__popularity__score"})
if target_elem:
    popularity_score = target_elem.get_text(strip=True)
    print(popularity_score)

如果需要批量查找多个匹配元素,把find换成find_all即可,返回的是元素列表,遍历后提取文本就行:

target_elements = soup.find_all(attrs={"data-testid": "hero-rating-bar__popularity__score"})
for elem in target_elements:
    print(elem.get_text(strip=True))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 17:06:27