puppeteer trigger click of button not working

Viewed 1188

I have a button nested in this video player that I am trying to simply click. Any idea how do i select?

     await page.waitForSelector('.icon-play');
        await page.click('.icon-play');
        await page.waitFor(6000);
    }
<a tabindex="-1" href="#" role="button" class="icon-play  comp largePlayBtn  largePlayBtnBorder" aria-label="Play clip" data-order="1" data-plugin-name="largePlayBtn" style="display: block;"></a>

2 Answers

I had the same problem a while back. A nested link inside a image.

This is due to the fact that the element needs to be visually clickable. You can perform a simple javascript click action using the HTMLElement.click() to bypass the puppeteer click action.

page.$eval(`HTMLElementSelector`, element =>
  element.click()
),

As you're clicking a link, which implies navigation you would want to englobe that inside a promise. Something like that should do the trick.

await Promise.all([
  page.$eval(`HTMLElementSelector`, element =>
    element.click()
  ),
  await page.waitForNavigation(),
]);

this answer is to make a clear understanding of why the puppeteer's click doesn't work sometimes.

Puppeteer's API has different semantics from the native browser API.

Puppeteer's page.click() seems like a straightforward wrapper on the browser's native HTMLElement.click(), but it actually operates quite differently.

working of page.click()

when we click using page.click() instead of invoking the click event handler directly on the element as the native HTMLElement.click() does

  • Puppeteer scrolls the element into view
  • moves the mouse onto the element
  • presses one of a few mouse buttons
  • optionally triggers a delay
  • then releases the mouse button

You can also trigger multiple clicks. In other words, Puppeteer performs a click like a human would.

That's why when we click page.click() it clicks at (x,y) position of the screen as a human would. So, sometimes we don't see expected results as it doesn't show any error and it shouldn't, we think that page.click() is not working.

So, the easiest solution is to use page.evaluate() and click with native browser API.

Solution

await page.evaluate(() => {
    document.querySelector('selector').click();
});
Related