【问题标题】:How to get the quantity of children inside the element using xpath query on the puppeter?如何在 puppeter 上使用 xpath 查询获取元素内子元素的数量?
【发布时间】:2020-10-17 22:04:39
【问题描述】:

我需要在 Puppeteer 中使用 page.$x(xpath) 函数获取元素内的子元素数量,我很生气我没有成功。在浏览器控制台中,我可以使用 $x().children.length 来完成。在使用节点的 puppeteer 中执行此操作的最佳方法是什么?

【问题讨论】:

  • 只需在 page.evaluate 中以同样的方式进行操作
  • 得到我预期的结果有点不同

标签: node.js xpath puppeteer


【解决方案1】:

您可以在page.evaluate() 中使用元素/JS 句柄 API 或纯 Web API。这些都是wways:

const puppeteer = require('puppeteer');

(async function main() {
  try {
    const browser = await puppeteer.launch();
    const [page] = await browser.pages();

    await page.goto('https://example.org/');

    const [element] = await page.$x('//body/div');
    const children = await element.getProperty('children');
    const length1 = await (await children.getProperty('length')).jsonValue();
    console.log(length1); // 3

    const length2 = await page.evaluate(() => {
      return document.evaluate(
        '//body/div', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE
      ).singleNodeValue.children.length;
    });
    console.log(length2); // 3

    await browser.close();
  } catch (err) {
    console.error(err);
  }
})();

【讨论】:

  • 我设法完成了您的第一个决议。但是你的方式更短,更美观,谢谢
猜你喜欢
  • 2012-12-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-24
  • 1970-01-01
  • 2016-04-13
  • 2017-04-16
  • 1970-01-01
  • 2018-07-09
相关资源
最近更新 更多