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:
<span class="styleNumber" data-Color="Blue">SG1000</span>
<span class="styleNumber" data-Color="Green">SG2000</span>
<span class="styleNumber" data-Color="Red">SG3000</span>
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
You can get attribute value with evaluate
method.
await page.evaluate('document.querySelector("span.styleNumber").getAttribute("data-Color")')
$$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"]
const styleNumbers = await page.$$("span.styleNumber");
for( let styleNumber of styleNumbers ) {
const attr = await page.evaluate(el => el.getAttribute("data-Color"), styleNumber);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With