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

Beautiful Soup遍历find_all结果无法获取标签post-id属性如何解决

Beautiful Soup获取标签自定义属性的正确方法

错误原因

你的代码返回None是因为重复查找逻辑错误:

  • 执行soup.find_all('article')后,循环中的变量a本身就是单个<article>标签对象
  • 循环内调用a.find('article', {'post-id':True})的作用是在当前a标签的子节点中查找嵌套的article元素,但示例HTML里所有article标签都是平级的,每个article内部没有子级article节点,自然匹配不到结果返回None。

正确实现代码

不需要二次调用find查找,直接对已经拿到的a标签对象取属性即可:

articles = soup.find_all('article')

for a in articles:
    post_id = a['post-id']
    print(post_id)

执行后输出结果:

123
456
789

兼容异常场景的写法

如果页面中可能存在不带post-id属性的article标签,直接用a['post-id']会触发KeyError,推荐用.get()方法取属性,属性不存在时默认返回None,不会中断程序:

articles = soup.find_all('article')

for a in articles:
    post_id = a.get('post-id')
    # 只处理存在post-id的标签
    if post_id:
        print(post_id)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 18:24:35