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

使用BeautifulSoup提取HTML标签中title属性值的方法

BeautifulSoup提取a标签title属性方法

find_all('a')返回的是包含所有a标签的Tag对象列表,你可以通过两种方式提取title属性值:

  • 方法一:遍历所有a标签,用get()方法安全提取(推荐,兼容无title属性的a标签)
# 提取所有存在title属性的a标签的title值,过滤无title的标签
title_list = [tag.get('title') for tag in soup.find_all('a') if tag.get('title')]
print(title_list)

get()方法的优势是,当标签不存在title属性时会返回None而不是抛出KeyError异常,配合if判断即可自动过滤掉没有title的标签,避免结果出现空值。
用你给出的示例HTML运行上述代码,输出结果为:
['Jammu and Kashmir (union territory)']

  • 方法二:查找时直接筛选带title属性的a标签
# 先筛选出所有带有title属性的a标签,再提取属性
a_with_title = soup.find_all('a', title=True)
title_list = [tag['title'] for tag in a_with_title]
print(title_list)

find_all中传入title=True参数时,只会返回带有title属性的a标签,后续直接按下标取属性也不会报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 18:30:01