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.
JavaScript
x
2
1
<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>
2
This is the full css selector taken from inspect
JavaScript
1
4
1
#focus-lock-id > div.sc-furwcr.lhriHG > div >
2
div.sc-bYoBSM.egarKh > div > div > div.sc-dlVxhl.bEDIID >
3
div > button:nth-child(3)
4
Here’s my code:
JavaScript
1
18
18
1
const puppeteer = require("puppeteer");
2
3
async function launch() {
4
const browser = await puppeteer.launch({
5
headless: false,
6
defaultViewport: false,
7
});
8
const page = await browser.newPage();
9
10
await page
11
.goto("", {
12
waitUntil: "networkidle0",
13
})
14
.catch((err) => console.log("error loading url", err));
15
page.click('button[data-testid="uc-deny-all-button"]');
16
}
17
launch();
18
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:
- The selector appears dynamically after the page has loaded, so you should
waitForSelector
rather than assumingnetworkidle0
will be enough to catch the button. - The selector you want is in a shadow root, so select the root and dip into it with
.shadowRoot
. - Your
.click()
call must beawait
ed.
JavaScript
1
23
23
1
const puppeteer = require("puppeteer"); // ^18.0.4
2
3
let browser;
4
(async () => {
5
browser = await puppeteer.launch({headless: true});
6
const [page] = await browser.pages();
7
const url = "https://www.partslink24.com/";
8
await page.goto(url, {waitUntil: "domcontentloaded"});
9
const rootSel = "#usercentrics-root";
10
const btnSel = 'button[data-testid="uc-deny-all-button"]';
11
const rootContainer = await page.waitForSelector(rootSel);
12
const root = await rootContainer.evaluateHandle(el => el.shadowRoot);
13
const btn = await root.waitForSelector(btnSel);
14
await btn.click();
15
await page.waitForFunction(`
16
!document.querySelector("${rootSel}").querySelector('${btnSel}')
17
`);
18
await page.screenshot({path: "test.png", fullpage: true});
19
})()
20
.catch(err => console.error(err))
21
.finally(() => browser?.close())
22
;
23