如何通过Denomination标识提取对应文本?解决爬取动态HTML问题
解决方案:通过「Denomination:」标识提取对应文本块
问题背景
爬取网页文档时,需要提取「Denomination:」后独立文本块的内容。原实现采用硬编码XPath依赖固定HTML层级,当文档结构变动时会出现提取错误,需改为基于「Denomination:」标识的动态定位方式。
改进实现
利用lxml的XPath定位「Denomination:」标签,再关联到对应的文本块,无需依赖固定的div索引。修改后的代码如下:
from lxml import etree class LTED: def __init__(self, url, soup): if not soup: soup = get_soup_from_url(url, "html.parser") self.dom = etree.HTML(str(soup)) # 判断是否为更新后的文档 self.corrigenda = bool(soup.body.findAll(text="Corrigenda")) self.denomination = self.get_denomination() def get_denomination(self): # 定位包含"Denomination:"的span,再找到相邻的txtmark下的有效文本 xpath_expr = "//span[text()='Denomination:']/../div[@class='txtmark']/p[normalize-space(text())]" items = self.dom.xpath(xpath_expr) if items: return items[0].text.strip() return None
代码说明
- XPath逻辑:
//span[text()='Denomination:']:精准定位显示「Denomination:」的span元素../div[@class='txtmark']:找到该span的父元素下的txtmark容器(即文本块所在位置)p[normalize-space(text())]:筛选txtmark下非空的p标签,避免提取空白内容
- 优势:不再依赖固定的div层级索引,只要「Denomination:」与对应文本块的关联结构不变,就能稳定提取内容,适配HTML结构的变动。
内容的提问来源于stack exchange,提问作者David Jimenez
相关产品推荐
相关产品推荐

