Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click checkbox with puppeteer via element ID

I have this puppeteer code:

(async () => {
  const browser = await puppeteer.launch({ args: ['--no-sandbox'] });
  const page = await browser.newPage();

  await page.goto("https://myurl.com/page");
  await page.waitForSelector("#select-all-checkbox");

  var bodyHTML = await page.content();
  console.log(bodyHTML + "\n\n");

  await page.click("#select-all-checkbox");
  await page.close();
  await browser.close();
})();

Logging the HTML to the console, I have verified the page I am accessing has this HTML:

<label><input type="checkbox" name="" id="select-all-checkbox" value="" checked=""><span class="ifaFs"><span data-testid="icon-checkbox-someselected" class="hdDWuD"></span></span></label>

I am receiving this error on the page.click line:

(node:3827) UnhandledPromiseRejectionWarning: Error: Node is either not visible or not an HTMLElement
at ElementHandle._clickablePoint (/path/to/node_modules/puppeteer/lib/JSHandle.js:217:13)
at process._tickCallback (internal/process/next_tick.js:68:7)
-- ASYNC --
at ElementHandle. (/path/to/node_modules/puppeteer/lib/helper.js:111:15)
at DOMWorld.click (/path/to/node_modules/puppeteer/lib/DOMWorld.js:367:18)
at process._tickCallback (internal/process/next_tick.js:68:7)
-- ASYNC --
at Frame. (/path/to/node_modules/puppeteer/lib/helper.js:111:15)
at Page.click (/path/to/node_modules/puppeteer/lib/Page.js:1037:29)

like image 725
C0NFUS3D Avatar asked Oct 11 '19 18:10

C0NFUS3D


People also ask

How do I check if a checkbox is checked in puppeteer?

Handle Checkbox in Puppeteer To avoid that we have to check whether a checkbox is already checked or not, if checked then we should ignore it, but if not checked then we can click it and make the check box checked.


1 Answers

With my code example above, this was how I resolved the problem.

(async () => {
  const browser = await puppeteer.launch({ args: ['--no-sandbox'] });
  const page = await browser.newPage();

  await page.goto("https://myurl.com/page");
  await page.waitForSelector("#select-all-checkbox");

  await page.evaluate(() => {
    document.querySelector("#select-all-checkbox").parentElement.click();
  });

  await page.close();
  await browser.close();
})();
like image 71
C0NFUS3D Avatar answered Oct 05 '22 07:10

C0NFUS3D