在 Puppeteer 中获取 elementHandle 的兄弟

ber*_*tet 6 javascript puppeteer

我正在做

const last = await page.$('.item:last-child')
Run Code Online (Sandbox Code Playgroud)

现在我想根据 last 获取前面的元素。IE

const prev = last.$.prev()
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

Eve*_*tss 11

您应该使用previousElementSiblinginside evaluateHandle,如下所示:

const prev = await page.evaluateHandle(el => el.previousElementSibling, last);
Run Code Online (Sandbox Code Playgroud)

这是完整的示例:

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();
})();
Run Code Online (Sandbox Code Playgroud)