在Puppeteer中获得一个元素的兄弟

时间:2018-02-19 07:22:47

标签: javascript puppeteer

我正在做

const last = await page.$('.item:last-child')

现在我喜欢根据最后一个获得前面的元素。即

const prev = last.$.prev()

关于如何做到这一点的任何想法?

谢谢!

1 个答案:

答案 0 :(得分:2)

您应该在previousElementSibling内使用evaluateHandle,如下所示:

const prev = await page.evaluateHandle(el => el.previousElementSibling, last);

以下是完整示例:

const puppeteer = require('puppeteer');

const html = `
<html>
    <head></head>
    <body>
        <div>
            <div class="item">item 1</div>
            <div class="item">item 2</div>
            <div class="item">item 3</div>
        </div>
    </body>
</html>`;

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto(`data:text/html,${html}`);

    const last = await page.$('.item:last-child');
    const prev = await page.evaluateHandle(el => el.previousElementSibling, last);

    console.log(await (await last.getProperty('innerHTML')).jsonValue()); // item 3
    console.log(await (await prev.getProperty('innerHTML')).jsonValue()); // item 2

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