FabricioG
FabricioG

Reputation: 3310

Attempting to click on a button but not working for me

I have the following code:

<div class="pt6-sm pb6-sm ta-sm-r d-sm-flx flx-jc-sm-fe"><button class="mb1-sm css-bz0cep ex41m6f0 secondary" type="button">Cancel</button><button class="ml3-sm mb1-sm css-17hmqcn ex41m6f0 primary" type="button">Save</button></div>

I'm attempting to click on the save button and I'm trying this:

  const addBtn = await select(page).getElement('button:contains(Save)');
  await addBtn.click()

I have also tried:

  const [button] = await page.$x("//div[@class='elements']/button[contains(., 'Save')]");
  if (button) {
      await button.click();
  }

I get an unhandled promise rejection. Any idea why?

Upvotes: 2

Views: 138

Answers (1)

theDavidBarton
theDavidBarton

Reputation: 8841

Basically you get the UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'click' of undefined until either your selector is not correct / element doesn't exist or it haven't yet appeared on the page.

In this case it seems your xpath selector was not grabbing the element.

That will do the job:

  const addBtn = await page.$x('//button[contains(text(), "Save")]')
  await addBtn[0].click()

Did you know? If you right click on an element in Chrome DevTools "Elements" tab and you select "Copy": there you are able to copy the exact selector or xpath of an element. After that you can switch to the "Console" tab and with the Chrome api you are able to test the selector's content, so you can prepare it for your puppeteer script. E.g.: $x('//button[contains(text(), "Save")]').textContent should show the text of the button that you've expected to click on, otherwise you need to change on the access, or you need to check if there are more elments with the same selector etc. This may helps you to find more appropriate selectors.

Upvotes: 3

Related Questions