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

如何用BeautifulSoup通过文本内容获取对应标签及其父标签?

使用BeautifulSoup根据文本反向查找标签及父标签

你可以借助BeautifulSoup的自定义匹配逻辑实现反向查找,核心是定位包含目标文本的标签,具体实现如下:

1. 查找包含指定文本的标签

通过find方法配合匿名函数作为过滤器,精准匹配包含目标文本的标签:

# 查找包含"Top Rated Movies"的标签
target_tag = soup.find(lambda tag: tag.string and "Top Rated Movies" in tag.string.strip())
if target_tag:
    print(target_tag.name)  # 输出:h1

2. 获取标签的父标签

找到目标标签后,直接调用.parent属性就能拿到它的父标签:

if target_tag:
    parent_tag = target_tag.parent
    print(parent_tag.name)  # 输出父标签名称,比如 div、body 等

注意事项

  • 用strip()处理文本是为了忽略前后空白,避免因空格、换行导致匹配失败
  • 如果要查找所有符合条件的标签,把find替换成find_all即可,返回结果为标签列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 01:05:19