简体   繁体   中英

how do you loop through checkboxes using puppeteer?

I have a list of checkboxes, every time puppeteer run the test I need to:

  • if a box is already selected then move to next box and select it, and if the next is selected move to the next checkbox and so on

复选框示例

if(await page.$eval(firstcheckbox, check=>check.checked =true)) { //check if the box is selected await page.waitForSelector(do something, ele=>elem.click())//if the checkbox is already selected, move to the second row and select a undecked box

}else if{

await page.$eval(firstcheckbox, check=>check.checked =false)){ //if the checkbox is not ticked await page.$eval(clickcheckbox, elem=>elem.click);//tick the checkbox

You can use all the testing and changing inside one page.evaluate() :

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch({ headless: false, defaultViewport: null });

const html = `
  <!doctype html>
  <html>
    <head><meta charset='UTF-8'><title>Test</title></head>
    <body>
      <input type="checkbox" id="checkbox1"><label for="checkbox1">checkbox1</label><br>
      <input type="checkbox" id="checkbox2" checked><label for="checkbox2">checkbox2</label><br>
      <input type="checkbox" id="checkbox3" checked><label for="checkbox3">checkbox3</label><br>
      <input type="checkbox" id="checkbox4"><label for="checkbox4">checkbox4</label><br>
    </body>
  </html>`;

try {
  const [page] = await browser.pages();

  await page.goto(`data:text/html,${html}`);

  await page.evaluate(() => {
    for (const checkbox of document.querySelectorAll('input')) {
      if (!checkbox.checked) checkbox.click();
    }
  });
  console.log('Done.');
} catch (err) { console.error(err); }

Or, if you need a loop over element handles, you can try this:

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch({ headless: false, defaultViewport: null });

const html = `
  <!doctype html>
  <html>
    <head><meta charset='UTF-8'><title>Test</title></head>
    <body>
      <input type="checkbox" id="checkbox1"><label for="checkbox1">checkbox1</label><br>
      <input type="checkbox" id="checkbox2" checked><label for="checkbox2">checkbox2</label><br>
      <input type="checkbox" id="checkbox3" checked><label for="checkbox3">checkbox3</label><br>
      <input type="checkbox" id="checkbox4"><label for="checkbox4">checkbox4</label><br>
    </body>
  </html>`;

try {
  const [page] = await browser.pages();

  await page.goto(`data:text/html,${html}`);

  for (const checkbox of await page.$$('input')) {
    if (!await checkbox.evaluate(elem => elem.checked)) {
      await checkbox.click();
    }
  }
  console.log('Done.');
} catch (err) { console.error(err); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM