我想同时抓取多个 url,所以我曾经p-queue实现一个Promise-queue。
例如,请参阅下面的代码,使用 1 个浏览器和多个页面来完成此工作。
const queue = new PQueue({
concurrency: 5
});
(
async () => {
let instance = await pptr.launch({
headless: false,
});
// task processor function
const createInstance = async (url) => {
let page = await instance.newPage();
await page.goto(email);
// (PROBLEM) more operations go here
...
return await page.close();
}
// add tasks to queue
for (let url of urls) {
queue.add(async () => createInstance(url))
}
}
)()
Run Code Online (Sandbox Code Playgroud)
问题是,确实可以通过多个页面同时打开多个网址,但看起来只有浏览器聚焦的一个(且只有一个)页面会继续执行操作(请参阅上面的代码部分more operations go here),另一个页面(或选项卡)只会停止工作,除非我单击该页面来关注它。
那么有没有办法同时运行所有页面呢?
我发现为什么上面的代码不起作用,我不应该await instance在工作函数之外,而应该await在内部,见下文,
(
async () => {
let instance = pptr.launch({ // don't await here
headless: false,
});
// task processor function
const createInstance = async (url) => {
let real_instance = await instance; // await here
let page = await real_instance.newPage();
await page.goto(email);
// (PROBLEM) more operations go here
...
return await page.close();
}
// add tasks to queue
for (let url of urls) {
queue.add(async () => createInstance(url))
}
}
)()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7054 次 |
| 最近记录: |