Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the sibling of an elementHandle in Puppeteer

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!

like image 527
bernatfortet Avatar asked Feb 19 '18 07:02

bernatfortet


People also ask

How do you get a list of puppeteer elements?

You can get the elements by using the class in puppeteer, but the puppeteer does not understand what is class or id; so you have to use the CSS format to make the puppeteer understand it. Use . (dot) before the class name to denote that the following is class.

How do you get the inner text on a puppeteer?

We can get element text in Puppeteer. This is done with the help of the textContent property. This property of the element is passed as a parameter to the getProperty method.

How do you find the value of an element in a puppeteer?

page. $eval() function is used to get the value for an element in puppeteer. $eval will stage two-parameter as an argument first parameter will be the selector and the second parameter will be element= element.


1 Answers

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();
})();
like image 58
Everettss Avatar answered Nov 12 '22 07:11

Everettss