首页 > 解决方案 > 无法让 puppeteer 重用同一浏览器浏览新收集的链接

问题描述

我已经创建了一个node脚本puppeteer从网站的登录页面抓取不同帖子的链接,我的脚本完美地做到了这一点。尽管该站点的内容是静态的,但我使用 puppeteer 来查看它的性能,因为我对此很陌生。

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

到目前为止,这是我的尝试:

const puppeteer = require("puppeteer");

(async () => {
    const browser = await puppeteer.launch({headless:false});
    const [page] = await browser.pages();
    await page.goto("https://stackoverflow.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;
})();

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

标签: node.jsweb-scrapingpuppeteer

解决方案


您可以为您收集的链接重用现有页面并在关闭浏览器之前对其进行迭代:

const puppeteer = require("puppeteer");

(async () => {
    const browser = await puppeteer.launch({headless:false});
    const [page] = await browser.pages();
    await page.goto("https://stackoverflow.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);

    // ...
})();

推荐阅读