在 Puppeteer 中获取 elementHandle 的兄弟 [英] Getting the sibling of an elementHandle in Puppeteer

查看:77
本文介绍了在 Puppeteer 中获取 elementHandle 的兄弟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做

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

现在我想根据 last 获取前面的元素.即

const prev = last.$.prev()

对如何做到这一点有任何想法吗?

谢谢!

解决方案

你应该使用 previousElementSibling 位于 evaluateHandle,像这样:

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

以下是完整示例:

const puppeteer = require('puppeteer');const html = `<头></头><身体><div><div class="item">item 1</div><div class="item">item 2</div><div class="item">item 3</div>

`;(异步() => {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());//第 3 项console.log(await (await prev.getProperty('innerHTML')).jsonValue());//第 2 项等待 browser.close();})();

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!

解决方案

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

这篇关于在 Puppeteer 中获取 elementHandle 的兄弟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆