How to select a button with multiple class names and specific aria-label in puppeteer js?

Viewed 2183

I am trying to click this button but I keep failing as there is also another button with the same class name with a different aria-name or I am just clicking it wrongly.

<button aria-label="upvote" aria-pressed="false" class="voteButton _2m5vzALl8kQdr9kwIFUo5t" data-click-id="upvote"><span class="_3wVayy5JvIMI67DheMYra2 _3SUsITjKNQ7Tp0Wi2jGxIM _22nWXKAY6OzAfK5GcUqWV2 qW0l8Af61EP35WIG6vnGk _3edNsMs0PNfyQYofMNVhsG"><i class="icon icon-upvote _2Jxk822qXs4DaXwsN7yyHA _39UOLMgvssWenwbRxz_iEn"></i></span></button>

my code looks like this at the moment :

  await page.waitForSelector('.voteButton._2m5vzALl8kQdr9kwIFUo5t');
  await page.click('.voteButton._2m5vzALl8kQdr9kwIFUo5t');

How can I click an element specifically for aria-label or data-click-id?

2 Answers

You might have some other problem with your use case as your script should already work as expected: clicks the first element instance with the given selector (if there is a 2nd or 3rd instance: it won't touch them).

It is possible to select elements based on their specific attributes (including aria attributes) with Attribute selectors:

await page.waitForSelector('button[aria-label="upvote"]')
await page.click('button[aria-label="upvote"]')

You must be independent from hash names like _3wVayy5JvIMI67DheMYra2 This names will be change after rebuild

You need use for your case some fixed classes like 'button[class~="voteButton"]'

And don't forget check your selector on page in console before run puppeteer:

document.querySelector('button[class~="voteButton"]');

then you can run puppeteer:

await page.waitForSelector('button[class~="voteButton"]');
await page.click('button[class~="voteButton"]');
Related