Skip to content
Advertisement

Can’t locate and click on a terms of conditions button

I am new to pupeeteer and first what i am trying to do is loading a page and clicking on a button. However, it can’t locate the element. I assume this is because I need to locate the parent or parent’s parent element.

<button role="button" data-testid="uc-accept-all-button" class="sc-gsDKAQ fHGlTM" style="border: 2px solid rgb(247, 196, 0); padding: 0.375rem 1.125rem; margin: 0px 6px;">Accept All</button>

This is the full css selector taken from inspect

#focus-lock-id > div.sc-furwcr.lhriHG > div > 
div.sc-bYoBSM.egarKh > div > div > div.sc-dlVxhl.bEDIID > 
div > button:nth-child(3)

Here’s my code:

const puppeteer = require("puppeteer");

async function launch() {
  const browser = await puppeteer.launch({
    headless: false,
    defaultViewport: false,
  });
  const page = await browser.newPage();

  await page
    .goto("", {
      waitUntil: "networkidle0",
    })
    .catch((err) => console.log("error loading url", err));
  page.click('button[data-testid="uc-deny-all-button"]');
}
launch();

It’s a simple accept and conditions block where I would want to click on an “Accept all” button to close it and proceed further. What usual actions do I need to wait for the parent element first then dig further? Or there is an easy way?

This is the website I am trying to close terms and conditions for: https://www.partslink24.com/

Advertisement

Answer

A few problems:

  1. The selector appears dynamically after the page has loaded, so you should waitForSelector rather than assuming networkidle0 will be enough to catch the button.
  2. The selector you want is in a shadow root, so select the root and dip into it with .shadowRoot.
  3. Your .click() call must be awaited.
const puppeteer = require("puppeteer"); // ^18.0.4

let browser;
(async () => {
  browser = await puppeteer.launch({headless: true});
  const [page] = await browser.pages();
  const url = "https://www.partslink24.com/";
  await page.goto(url, {waitUntil: "domcontentloaded"});
  const rootSel = "#usercentrics-root";
  const btnSel = 'button[data-testid="uc-deny-all-button"]';
  const rootContainer = await page.waitForSelector(rootSel);
  const root = await rootContainer.evaluateHandle(el => el.shadowRoot);
  const btn = await root.waitForSelector(btnSel);
  await btn.click();
  await page.waitForFunction(`
    !document.querySelector("${rootSel}").querySelector('${btnSel}')
  `);
  await page.screenshot({path: "test.png", fullpage: true});
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close())
;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement