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

Puppeteer中如何使用following-sibling定位后续兄弟节点并获取h6标签

定位实现方案

XPath 方案(基于following-sibling轴)

以下两种写法可根据匹配精度需求选择:

  • 匹配目标div之后所有同级div下的h6标签:
    //div[contains(@class, "MuiCardHeader-root")]/following-sibling::div//h6
  • 仅匹配目标div之后第一个紧跟的同级div下的h6标签:
    //div[contains(@class, "MuiCardHeader-root")]/following-sibling::div[contains(@class, "MuiCardContent-root")][1]//h6

Puppeteer 调用示例:

// 取匹配到的第一个h6元素
const h6Elements = await page.$x('//div[contains(@class, "MuiCardHeader-root")]/following-sibling::div[contains(@class, "MuiCardContent-root")][1]//h6')
const targetH6 = h6Elements[0]

CSS 选择器方案(模拟following-sibling逻辑)

CSS 无原生following-sibling轴,可通过兄弟选择器实现同等效果:

  • 仅匹配紧跟在目标div后的第一个同级div下的h6标签:
    div[class*="MuiCardHeader-root"] + div[class*="MuiCardContent-root"] h6
  • 匹配目标div之后所有同级div下的h6标签:
    div[class*="MuiCardHeader-root"] ~ div[class*="MuiCardContent-root"] h6

Puppeteer 调用示例:

const targetH6 = await page.$('div[class*="MuiCardHeader-root"] + div[class*="MuiCardContent-root"] h6')

提示:DOM结构中的jss开头类为动态生成的随机类,上述选择器均使用contains/*=匹配静态固定类前缀,可避免动态类变更导致选择器失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 02:15:03