Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all the child elements values of an html element using puppeteer

I am using puppeteer . I want to get the values of column names of a table.

<tbody>
<tr class="GridHeader" align="center" style="background-color:Black;">
    <td class="HeaderStyleOfdatalist">XYZ</td>
    <td>0500</td>
    <td>0550</td>
    <td>0600</td>
    <td>0650</td>
</tr>
</tbody>

What I need to get is an array of these td values. I tried page.$(selector) but could not understand the output. I also tried:

let idAttribute = await page.$eval('.GridHeader', e => e.childNodes);
console.log(idAttribute)

But not able to get the array of these td values.

Can you please help me loop over these values.

EDIT: Found the answer to the problem and posted it in the answers section.

like image 234
Aman Gupta Avatar asked Sep 09 '17 07:09

Aman Gupta


People also ask

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.

How do you get a list of puppeteer elements?

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.


1 Answers

I was able to get the solution using:

const data = await page.evaluate(() => {
        const tds = Array.from(document.querySelectorAll('.GridHeader td'))
        return tds.map(td => td.textContent)
    });

console.log(data) // ['xyz', '0500', '0550','0600', '0650']
like image 103
Aman Gupta Avatar answered Nov 15 '22 23:11

Aman Gupta