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

如何用BeautifulSoup提取指定ul标签中a元素的title属性值?

解决方法

你之前的代码无法生效是因为soup.find_all()返回的是ResultSet对象(本质是元素列表),不能直接在这个列表上调用.find_all(),必须遍历列表里的每个<ul>元素单独处理。

以下是可行的代码实现:

# 先获取所有目标ul标签
ul_list = soup.find_all('ul', class_='tags tags--project')

# 遍历每个ul,提取前2个title属性
all_titles = []
for ul in ul_list:
    # 找到当前ul下的所有a标签
    a_tags = ul.find_all('a')
    # 提取每个a的title,取前2个
    current_titles = [a.get('title') for a in a_tags[:2]]
    all_titles.extend(current_titles)

# 输出结果
print(all_titles)

补充说明

  • 如果某个<ul>内的<a>标签数量不足2个,a_tags[:2]会自动返回现有所有的title,不会报错。
  • 使用a.get('title')比a['title']更安全,当a标签没有title属性时,get()会返回None而不是抛出异常。

内容的提问来源于stack exchange,提问作者Weierstraß Ramirez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 00:01:03