node.js - 无法让 puppeteer 使用同一浏览器浏览新收集的链接

标签 node.js web-scraping puppeteer

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

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

这是我迄今为止的尝试:

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;
})();

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

最佳答案

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

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);

    // ...
})();

关于node.js - 无法让 puppeteer 使用同一浏览器浏览新收集的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55519750/

相关文章:

javascript - 如何使用 Electron webContents.print([options], [callback]) 打印 html/文本文件?

c# - 为什么 element.click() 在 Cefsharp 中不起作用?

node.js - puppeteer 操作错误 : Navigation failed because browser has disconnected

node.js - Puppeteer 无法在谷歌云功能中工作

node.js - 我可以从 Socket.io 访问 cookie 吗?

javascript - express/NodeJS 上的 CORS 问题,Internet Explorer 不提供服务

Go 语言刮刀。如何抓取网站上动态生成的链接?

javascript - 是否可以在 nodejs+puppeteer 中包含一个源文件来添加功能?

node.js - 匹配API和同构路由

python - 读取文件时字符串索引超出范围