如何使用BeautifulSoup爬取title-class标签间及末尾的无规则动态内容?
平级节点场景下的BeautifulSoup内容提取方案
实现逻辑
- 依赖平级节点的固定顺序定位,不需要匹配内容特征,完全按照
title-classdiv的位置做内容切片 - 先拿到唯一父容器下的所有平级子节点列表,记录所有
title-classdiv在列表中的索引值,按索引区间切分相邻两个title之间、最后一个title之后的全部内容
可直接复用的代码
基础节点定位
from bs4 import BeautifulSoup # page_source为已获取的页面HTML字符串,替换为你实际的请求返回内容 soup = BeautifulSoup(page_source, "html.parser") # 替换为你实际的唯一父容器类名,示例父类为`content-parent` parent = soup.find("div", class_="content-parent") # 将父容器下所有平级直接子节点转为有序列表 siblings = list(parent.children)
定位所有标题节点的位置
title_indexes = [] for idx, node in enumerate(siblings): # 跳过非标签的纯文本节点(比如换行、空白符) if not hasattr(node, "get"): continue # 匹配带title-class的div节点 if "title-class" in node.get("class", []): title_indexes.append(idx)
按区间切分对应内容
crawl_result = [] # 遍历所有标题位置,逐段提取内容 for pos_idx in range(len(title_indexes)): # 内容段起始位置:当前标题节点的下一个节点 seg_start = title_indexes[pos_idx] + 1 # 内容段结束位置:若为最后一个标题则取到列表末尾,否则取下一个标题的位置(不包含下一个标题本身) if pos_idx == len(title_indexes) - 1: seg_end = len(siblings) else: seg_end = title_indexes[pos_idx + 1] # 切出当前段的全部平级节点 segment_nodes = siblings[seg_start:seg_end] # 提取当前标题文本 current_title = siblings[title_indexes[pos_idx]].get_text(strip=True) # 按需处理当前段的内容,以下为示例:拼接为纯文本,也可保留节点HTML结构存入表格 seg_content = "\n".join( [node.get_text(strip=True) if hasattr(node, "get_text") else str(node).strip() for node in segment_nodes] ).strip() # 组装为和原采集流程一致的二维列表条目 crawl_result.append([current_title, seg_content])
注意事项
- 若存在两个相邻title紧挨着、中间无任何内容的情况,切分得到的段落为空,可根据需求设置默认填充值或跳过空段
- 若需要保留段落内的原始HTML结构存入表格,可直接将
str(segment_nodes)作为内容值存储,不需要转成纯文本 - 若匹配不到任何
title-class节点,title_indexes为空,可提前加判断返回空结果,避免后续循环报错
内容的提问来源于stack exchange,提问作者j-inc
相关产品推荐
相关产品推荐

