How can I extract a custom data attribute from an element using Puppeteer?

I am using Puppeteer for web scraping and have a button element with various attributes. I managed to capture its text content using a query selector, but now I need a method to obtain the value from a specific data attribute. For example, consider the following HTML:

<button class="btn full-width btn-secondary" data-role-id="login-btn" type="submit">
  <span class="label">Login</span>
</button>

I would like to know how to retrieve the value of the data attribute (in this case, the value of data-role-id) using Puppeteer. Any guidance on the correct approach would be appreciated.

Using Puppeteer, you can directly query the button and extract the custom data attribute using page.$eval. In my recent project involving web scraping with Puppeteer, I had to extract information from several custom attributes. For instance, I used code like this: const roleId = await page.$eval(‘button’, element => element.getAttribute(‘data-role-id’));. This approach worked reliably as long as the element is rendered by the time the query executes. It’s a neat and direct method to retrieve such attributes and has proved stable in multiple projects.