我需要通过page。$ x(xpath)函数获取元素内子元素的数量,这很不成功。在浏览器控制台中,我可以使用$ x()。children.length做到这一点。在带有节点的木偶中执行此操作的最佳方法是什么?
答案 0 :(得分:0)
您可以在page.evaluate()
中使用element / JS句柄API或纯Web API。它们都是:
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);
}
})();