'Get the Value of HTML Attributes Using Puppeteer $x selector

Since im trying to get HTML property for a element without class or ID

<span style="color: green">content</span>

I'm using $x selector:

const [data] = await page.$x('/html/body/div[2]/div/div/div[2]/div[1]/div/div/div[5]/div/div/table/tbody/tr/td[2]/table[1]/tbody/tr[2]/td[2]/span');

const style = await data.getProperty('style');
 
const pureStyle = await style.jsonValue();

But when I console.log pureStyle I receive as response:

{ '0': 'color' }


Solution 1:[1]

There is a simpliest way. You can get the span with document.querySelectorAll(). With this, you will have a list. Such as I don't know what return page.$x, maybe it return the same.

After, you have to get all style with style (what you do with getProperty). Such as you want only css content wrote in the html, you should use cssText and it will works fine.

Example:

var span = document.querySelectorAll("div div div span");
for(var element of span) {
  console.log(element.style.cssText);
}
<div>
  <div>
    <div>
       <span style="color: green; margin: 0;">span</span>
    </div>
  </div>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Elikill58