Getting the sibling of an elementHandle in Puppeteer

你说的曾经没有我的故事 提交于 2020-08-24 12:02:00

问题


I'm doing

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

Now I'd love to get the preceding element based on last. ie

const prev = last.$.prev()

Any thoughts on how to do this?

Thanks!


回答1:


You should use previousElementSibling inside evaluateHandle, like this:

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

Here is full example:

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();
})();


来源:https://stackoverflow.com/questions/48861261/getting-the-sibling-of-an-elementhandle-in-puppeteer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!