如何用BeautifulSoup提取h4标签内无类/ID的a标签href值?
解决方案:提取指定H4标签内A标签的标题与链接
报错原因分析
TypeError: 'NoneType' object is not callable 通常出现在以下场景:
- 误将
find()/find_all()返回的None对象当作方法调用(比如写成result()) - 变量名与BeautifulSoup的方法名冲突(比如用
find作为变量名,后续再调用find()时会指向None)
正确实现代码
假设目标HTML结构如下:
<h4 class="article_title_list"><a href="https://example.com/post1">Python爬虫入门指南</a></h4> <h4 class="article_title_list"><a href="https://example.com/post2">BeautifulSoup进阶技巧</a></h4>
使用BeautifulSoup的正确代码:
from bs4 import BeautifulSoup # 若从网络获取页面,需导入requests:import requests # 替换为你的HTML内容(或通过requests.get(url).text获取) html = """ <h4 class="article_title_list"><a href="https://example.com/post1">Python爬虫入门指南</a></h4> <h4 class="article_title_list"><a href="https://example.com/post2">BeautifulSoup进阶技巧</a></h4> """ soup = BeautifulSoup(html, "html.parser") # 定位所有class为article_title_list的h4标签 target_h4s = soup.find_all("h4", class_="article_title_list") for h4 in target_h4s: # 获取h4内部的a标签 a_tag = h4.find("a") # 避免a标签不存在导致的报错 if a_tag: # 提取标题文本(strip=True去除多余空格换行) title = a_tag.get_text(strip=True) # 提取href属性 link = a_tag.get("href") print(f"标题: {title} | 链接: {link}")
关键注意事项
- 匹配class属性时用
class_而非class(因为class是Python关键字) - 每次获取标签后先判断是否为
None,再调用属性或方法,避免报错 - 用
get_text(strip=True)获取干净的文本内容,get("href")安全提取属性(即使属性不存在也不会报错)
预期输出
标题: Python爬虫入门指南 | 链接: https://example.com/post1 标题: BeautifulSoup进阶技巧 | 链接: https://example.com/post2
内容的提问来源于stack exchange,提问作者user20083529
相关产品推荐
相关产品推荐

