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

如何用BeautifulSoup提取img alt属性文本?

用BeautifulSoup提取img标签的alt属性值列表

Hey there! Let's walk through how to get that list of alt values you need from your HTML snippet using BeautifulSoup.

Step 1: 确保你已经安装了BeautifulSoup

如果还没装,先通过pip完成安装:

pip install beautifulsoup4

Step 2: 编写代码解析HTML

这里直接用你提供的HTML内容来演示:

from bs4 import BeautifulSoup

# 你的HTML内容(还原转义后的标签)
html_content = '''<p class="number"> <img alt="1" src="/img/common_new/ball_1.png"/> <img alt="10" src="/img/common_new/ball_10.png"/> <img alt="13" src="/img/common_new/ball_13.png"/> <img alt="26" src="/img/common_new/ball_26.png"/> <img alt="32" src="/img/common_new/ball_32.png"/> <img alt="36" src="/img/common_new/ball_36.png"/> <span class="plus">+</span> <span class="number_bonus"><img alt="9" src="/img/common_new/ball_9.png"/> </span> </p>'''

# 初始化解析器
soup = BeautifulSoup(html_content, 'html.parser')

# 提取所有img标签的alt属性,转成整数后收集为列表
alt_values = [int(img['alt']) for img in soup.find_all('img')]

print(alt_values)
# 输出结果: [1, 10, 13, 26, 32, 36, 9]

代码逻辑解释

  • soup.find_all('img'):会抓取HTML里所有的<img>标签,不管它嵌套在哪个父元素里(包括那个number_bonus容器内的img)。
  • 列表推导式遍历每个img标签,通过img['alt']直接获取属性值,再用int()转换为整数,最终得到你需要的数字列表。

这个方法简洁高效,完全匹配你想要的结果~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:37:58