node.js - 无法让 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;
})();
我怎样才能纠正我的脚本,以便它遍历新收集的链接,重用同一个浏览器?
解决方案
您可以为您收集的链接重用现有页面并在关闭浏览器之前对其进行迭代:
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);
// ...
})();
推荐阅读
- java - 在进行更新之前获取最新的 ETag?
- python - 随机更改 numpy 数组值
- javascript - 如何解决设置 innerHTML 导致转义序列扩展的问题?
- git - 我可以创建仅包含单个开发人员或工作项的提交的 Git 拉取请求吗?
- flutter - 如何在两个小部件(文件)之间传递数据?
- ansible - 来自列表项的 Ansible 子字符串
- c++ - 在 C++ 中排序比较器
- android - 触摸视图时如何暂停和恢复kotlin协程?
- bash - 有没有办法创建一个基于数组更改布尔值的函数?
- amazon-cognito - 如何要求 Cognito 强制使用 SAML IDP 重新进行身份验证?