Get the Value of HTML Attributes Using Puppeteer

那年仲夏 提交于 2021-02-07 02:41:18

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/56467696/get-the-value-of-html-attributes-using-puppeteer

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