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

如何用BeautifulSoup获取<a>标签上方的h1、h2、h3元素

解决方法

1. 获取标签上方最近的同级标题元素

如果标题与的父元素属于同级节点,可使用find_previous()方法直接指定查找h1/h2/h3标签:

from bs4 import BeautifulSoup

html = '''
<h1>主标题</h1>
<p>介绍内容</p>
<h2>章节标题</h2>
<div>
  <a href="example.com">目标链接</a>
</div>
'''

soup = BeautifulSoup(html, 'html.parser')
target_a = soup.find('a', href='example.com')

# 查找上方最近的h1/h2/h3
closest_title = target_a.find_previous(['h1', 'h2', 'h3'])
if closest_title:
    print(f"对应标题: {closest_title.get_text(strip=True)}")
else:
    print("未找到对应标题")

2. 遍历标签的所有前置兄弟元素

若需要收集标签上方所有符合条件的标题(而非仅最近一个),可通过previous_siblings遍历筛选:

# 承接上面的soup和target_a对象
all_above_titles = []
for sibling in target_a.previous_siblings:
    if sibling.name in ['h1', 'h2', 'h3']:
        all_above_titles.append(sibling.get_text(strip=True))
# 由于previous_siblings是倒序返回,需反转得到正常顺序
all_above_titles.reverse()
print(f"所有上方标题: {all_above_titles}")

3. 处理嵌套结构下的标题

如果标签嵌套在子容器中,标题位于父容器或祖先节点内,可先定位的父容器,再向上查找标题:

html = '''
<div class="content">
  <h2>章节标题</h2>
  <div class="links">
    <a href="link1">链接1</a>
    <a href="link2">链接2</a>
  </div>
</div>
'''

soup = BeautifulSoup(html, 'html.parser')
target_a = soup.find('a', href='link1')

# 先定位共同祖先容器,再在容器内查找标题
parent_container = target_a.find_parent('div', class_='content')
if parent_container:
    title = parent_container.find(['h1', 'h2', 'h3'])
    if title:
        print(f"对应标题: {title.get_text(strip=True)}")

关键说明

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 04:32:11