首页 > 解决方案 > 选择多个复选框在 Puppeteer 无头浏览器中不起作用

问题描述

在下面的代码中,我使用无头浏览器访问https://example.com/careers站点并选择两个复选框并提取结果数据。但是这里的问题是只有第一个复选框(technologycheckbox)被选中,而另一个复选框(locationcheckbox)没有被选中。请帮忙

(async () => {
  const browser = await puppeteer.launch({headless:false});
  const page = await browser.newPage();
  await page.setViewport({ width: 1366, height: 768});
  await page.goto('https://example.com/careers' ,{waitUntil: 'networkidle2'});
  await page.waitFor(4000);

    const technologycheckbox = await page.$('#checkbox2idvalue');
    await page.waitFor(2000);
    page.waitForSelector(locationcheckbox);
    await technologycheckbox.click();
    await page.waitFor(15000);
    const locationcheckbox  = await page.$('#checkbox1idvalue');
    await locationcheckbox.click();
    await page.waitFor(9000);



const result = await page.evaluate(() => {


    let data = []; // Create an empty array that will store our data
    let elements = document.querySelectorAll("div>ul> li >div:nth-child(1)"); // Select all Products
    console.log(elements)

    for (var element of elements){ // Loop through each proudct

        let title = element.textContent;
        let url = element.href; // Select the title


        data.push({title, url}); // Push an object with the data onto our array
    }

    return data; // Return our data array

});

});

标签: node.jscheckboxpuppeteer

解决方案


运行部件时,您的变量locationcheckbox未定义page.waitForSelector(locationcheckbox);。您对 api 的使用似乎是正确的,因此请先解决此问题,然后它应该可以正常工作。


推荐阅读