如何用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
相关产品推荐
相关产品推荐

