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

如何在Puppeteer中通过指定XPath获取对应节点的数值内容

Puppeteer 通过XPath获取节点数值的实现方案

Puppeteer 提供了page.$x方法专门用于匹配XPath对应的元素,结合元素属性取值即可拿到目标数值,完整实现代码如下:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  // 替换为你的目标页面地址
  await page.goto('https://target-website.com');

  // 等待目标节点渲染完成,避免未加载导致匹配失败
  await page.waitForXPath('/html/body/main/section/section/div[2]/div/div/section[2]/div[2]/section/div[2]/ul/li[1]/div/div[2]/div[3]/span[2]');
  // $x返回匹配到的元素数组,此处用解构赋值拿到第一个匹配结果
  const [targetSpan] = await page.$x('/html/body/main/section/section/div[2]/div/div/section[2]/div[2]/section/div[2]/ul/li[1]/div/div[2]/div[3]/span[2]');
  // 提取元素文本内容并去空格
  const targetValue = await targetSpan.evaluate(el => el.textContent.trim());

  console.log(targetValue); // 输出结果:1,400
  await browser.close();
})();

如果需要直接使用你提供的包含text()的原始XPath取值,也可以通过页面内置的XPath解析方法实现:

const targetValue = await page.evaluate(() => {
  const xpathRes = document.evaluate(
    '/html/body/main/section/section/div[2]/div/div/section[2]/div[2]/section/div[2]/ul/li[1]/div/div[2]/div[3]/span[2]/text()',
    document,
    null,
    XPathResult.STRING_TYPE,
    null
  );
  return xpathRes.stringValue.trim();
});

注意:你使用的绝对XPath稳定性较差,页面嵌套结构、元素顺序稍有变动就会失效,有条件的话建议优先使用带特征匹配的相对XPath替代,比如//span[@class="currency-coins value"],可以大幅提升定位的鲁棒性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:06:03