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

