您可以在其中使用所有测试和更改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); }
或者,如果您需要元素句柄的循环,您可以试试这个:
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); }