遍历通过XPath选择的元素的子元素

时间:2020-08-09 03:10:49

标签: javascript node.js arrays foreach puppeteer

我试图遍历第一个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

0 个答案:

没有答案