Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the Value of HTML Attributes Using Puppeteer

Using Puppeteer, I've selected some HTML elements using:

await page.$$( 'span.styleNumber' );

I can get the element's text using:

console.log( await ( await styleNumber.getProperty( 'innerText' ) ).jsonValue() );

How can I the value of the element's data-Color attribute?

Here is my script:

HTML

<span class="styleNumber" data-Color="Blue">SG1000</span>
<span class="styleNumber" data-Color="Green">SG2000</span>
<span class="styleNumber" data-Color="Red">SG3000</span>

Puppeteer

const puppeteer = require( 'puppeteer' );

( async() => {
    const browser = await puppeteer.launch();

    const page = await browser.newPage();

    await page.goto( 'http://www.example.com/sample.php' );

    // Get a list of all elements.
    var styleNumbers = await page.$$( 'span.styleNumber' );

    // Print the style numbers.
    for( let styleNumber of styleNumbers ) {
        try {
            console.log( await ( await styleNumber.getProperty( 'innerText' ) ).jsonValue() );
        }
        catch( e ) {
            console.log( `Could not get the style number:`, e.message );
        }
    }

    await browser.close();
} )();

The above code would print:

SG1000
SG2000
SG3000

How can I get the value of the data-Color attributes? E.g.:

console.log( await ( await styleNumber.getAttribute( 'data-Color' ) ) ); // Blue
like image 384
GTS Joe Avatar asked Jun 05 '19 20:06

GTS Joe


1 Answers

You can get attribute value with evaluate method.

await page.evaluate('document.querySelector("span.styleNumber").getAttribute("data-Color")')

Second way

$$eval method can also be used. Also attributes called as Array from variable

const attr = await page.$$eval("span.styleNumber", el => el.map(x => x.getAttribute("data-Color")));

Output will be

["Blue", "Green", "Red"]

Your solution

const styleNumbers = await page.$$("span.styleNumber");

for( let styleNumber of styleNumbers ) {
    const attr = await page.evaluate(el => el.getAttribute("data-Color"), styleNumber);
}
like image 108
Abdulsamet Kurt Avatar answered Nov 15 '22 11:11

Abdulsamet Kurt