
本文介绍如何通过xpath的following-sibling轴定位紧邻的兄弟元素,特别适用于从带标签的html结构中提取关联数据(如“monthly:”后紧跟的数值内容),避免依赖固定索引,提升选择器健壮性。
本文介绍如何通过xpath的following-sibling轴定位紧邻的兄弟元素,特别适用于从带标签的html结构中提取关联数据(如“monthly:”后紧跟的数值内容),避免依赖固定索引,提升选择器健壮性。
在实际网页解析(如使用Selenium、Scrapy或lxml)中,我们常遇到语义化但无唯一ID或class的HTML结构。例如以下片段:
<div class="my-3"> <div class="d-flex justify-content-between">Monthly:</div> <div>0 / 30,000</div> </div>
目标是可靠地提取第二个 此时,最稳健的方式是以可识别的标签文本为锚点,再沿DOM关系导航。你已成功用 //*[normalize-space()='Monthly:'] 定位到第一个 接下来,要获取其下一个同级 ✅ 该表达式含义清晰: ⚠️ 注意事项: ? 实际应用示例(Python + lxml): 总结:面向语义而非结构的位置索引,是构建高鲁棒XPath表达式的核心原则。following-sibling轴让“标签+值”的关联提取变得直观、稳定且易于维护。//*[normalize-space()='Monthly:']/following-sibling::div
from lxml import html
doc = html.fromstring(html_content)
target_div = doc.xpath("//*[normalize-space()='Monthly:']/following-sibling::div")
if target_div:
value = target_div[0].text_content().strip() # → "0 / 30,000"
print(value)











