无法让人偶操纵者使用同一浏览器浏览新收集的链接

Unable to let puppeteer browse newly collected links reusing the same browser

我在 node 中结合 puppeteer 创建了一个脚本,用于从站点的登录页面抓取不同帖子的链接,我的脚本完美地完成了这项工作。尽管该站点的内容是静态的,但我还是使用 puppeteer 来查看它的性能,因为我对此还很陌生。

我现在想做的是利用这些链接遍历不同的页面,重复使用同一个浏览器,而不从新页面上抓取任何东西。但是,我无法修改我的脚本以反映相同的内容。

这是我目前的尝试:

const puppeteer = require("puppeteer");

(async () => {
    const browser = await puppeteer.launch({headless:false});
    const [page] = await browser.pages();
    await page.goto("https://whosebug.com/questions/tagged/web-scraping");
    page.waitFor(".summary");
    const sections = await page.$$(".summary");
    let data = [];
    for (const section of sections) {
        const itemName = await section.$eval(".question-hyperlink", el => el.href);
        data.push(itemName);
    }
    browser.close();
    return data;
})();

我怎样才能纠正我的脚本,以便它遍历新收集的链接,重复使用同一个浏览器?

您可以为您收集的链接重用现有页面,并在关闭浏览器之前迭代它们:

const puppeteer = require("puppeteer");

(async () => {
    const browser = await puppeteer.launch({headless:false});
    const [page] = await browser.pages();
    await page.goto("https://whosebug.com/questions/tagged/web-scraping");
    page.waitFor(".summary");
    const sections = await page.$$(".summary");
    let data = [];
    for (const section of sections) {
        const itemName = await section.$eval(".question-hyperlink", el => el.href);
        data.push(itemName);
    }

    // iterate over the URLs
    for (const url of data) {
        await page.goto(url);
    }

    await browser.close();
    return data;
})();

具有单独功能的替代方案

const puppeteer = require("puppeteer");

async function crawlUrls(data, page) {
    for (const url of data) {
        await page.goto(url);
    }
}

(async () => {
    // ...

    // iterate over the URLs
    await crawlUrls(data, page);

    // ...
})();