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

