首页 > 解决方案 > 遍历通过 XPath 选择的元素的子元素

问题描述

我正在尝试遍历第一个 div 元素的子元素并获取 textContent 属性。我可以只使用常规的 querySelectorAll ($$),然后遍历该数组。但是,我需要它遍历为使用 XPath 选择的子项创建的数组。现在我有这个代码:

<html>
    <head>

    </head>
    <body>
        <div>
            <div>This is the first div</div>
            <div>This is the second div</div>
            <div>This is the third div</div>
        </div>

    </body>

</html>

这是 JavaScript

const puppeteer = require('puppeteer');

(async () => {
const browser = await puppeteer.launch({
    headless: false,
});
const page = await browser.newPage();
await page.goto('http://127.0.0.1:5500/index.html');

await page.waitForXPath(('/html/body/div/div[2]'))
const [liveDiv] = await page.$x('/html/body/div/div[2]');
const [liveDivParent] = await liveDiv.$x('..');
const childArr = await liveDivParent.$x('/*')

childArr.forEach(async (el) => {

    const textC =  await el.getProperty('textContent');
    const textJ =  await textC.jsonValue();
    console.log(textJ)
})


await browser.close();
})();

现在的问题是,当它将所有内容放入单个对象时,forEach 仅控制台一次记录所有内容

            hello
            Wasasp
            LOL

不是在每个循环中列出它们,而是在早上 5 点,我已经筋疲力尽,但非常沮丧,我无法弄清楚。如果您有任何提示或建议,我非常感谢!感谢:D

标签: javascriptnode.jsarraysforeachpuppeteer

解决方案


推荐阅读