用BeautifulSoup实现HTML标题与对应段落的正确分层提取
问题根因
现有代码的逻辑缺陷来自item.find_next_siblings('p')的无边界匹配:它会抓取当前标题元素后方所有同级的p标签,不受后续出现的其他标题分隔限制,最终会导致每个条目的text列表不断混入属于其他标题的段落内容,出现错配、内容冗余的混乱输出。
修正思路
放弃“按标题反向找后续所有p”的逻辑,改为按文档从上到下的顺序遍历所有节点,维护一个当前正在关联的条目对象:
- 遇到标题标签时,先把已完成内容收集的上一个条目存入结果列表,再初始化新的条目承载当前标题
- 遇到p标签时,将段落文本追加到当前激活的条目下
- 遍历完全部节点后,将最后一个未存入的条目补入结果列表
可直接运行的修正代码
import json from bs4 import BeautifulSoup html = """ <h1>a Complexity Profile</h1> <p>Since time immemorial humans have...</p> <p>How often have we been told</p> <h2>INDIVIDUAL AND COLLECTIVE BEHAVIOR</h2> <p>Building a model of society based...</p> <p>All macroscopic systems...</p> <h3>COMPLEXITY PROFILE</h3> <p>It is much easier to think about the...</p> <p>A formal definition of scale considers...</p> <p>The complexity profile counts...</p> <h2>CONTROL IN HUMAN ORGANIZATIONS</h2> <p>Using this argument it is straightforward...</p> <h2>Conclusion</h2> <p>There are two natural conclusions...</p> """ soup = BeautifulSoup(html, "lxml") data = [] current_entry = None # 按文档原始顺序遍历所有节点 for node in soup.body.contents: # 跳过无标签的空文本节点(换行、空白符等无效内容) if node.name is None: continue # 匹配各级标题,切换当前关联的条目 if node.name in [f"h{level}" for level in range(1, 7)]: if current_entry is not None: data.append(current_entry) current_entry = { "title": node.get_text(strip=True), "text": [] } # 匹配段落,追加到当前条目的文本列表 elif node.name == "p" and current_entry is not None: current_entry["text"].append(node.get_text(strip=True)) # 补入最后一个收集完成、未被存入结果的条目 if current_entry is not None: data.append(current_entry) print(json.dumps(data, indent=4, ensure_ascii=False))
运行上述代码的输出结构与预期完全一致,所有段落都准确匹配对应所属的标题,无内容错配、冗余问题。
内容的提问来源于stack exchange,提问作者SMTH
相关产品推荐
相关产品推荐

