所以我找到了一个网站,它有非常酷的图片,我想要刮掉一些它的数据。这个网站已经有5年没有更新了,我试着联系它的主人获取一些API,但是我没有得到任何回应。
无论如何,网站有类别,每个图片都有自己的页码;所以为了抓取每个图片,我需要转到每个类别,然后转到那个特定类别的每个页面。
下面是我的代码,但是我不能让for loop重置。
const {Cluster} = require('puppeteer-cluster');
const puppeteer = require('puppeteer');
let c = 0;
let z = 500;
(async () => {
process.setMaxListeners(5);
const cluster = await Cluster.launch({
maxConcurrency: 3 // max browsers to spawn at the same time
});
let b = 20;
for (let i = 0; i < b; i++) {
cluster.execute({i}, async () => {
let browser = await puppeteer.launch({headless: false});
// scraping code using the i and c values
await browser.close();
console.log(i);
if (i > b - 10) {
i = 0;
c = c + 1;
console.log('c = ' + c);
if (c > z)
process.exit();
}
});
}
await cluster.idle();
await cluster.close();
})();这是输出(顺序不是必需的):
1
0
2
4
3
5
6
7
8
9
10
11
c = 1
12
c = 2
13
c = 3
14
c = 4
16
c = 5
15
c = 6
17
c = 7
18
c = 8
19
c = 9
Process finished with exit code 0如果我在cluster.execute前面添加await,那么for loop将被重置,但是我不能同时使用多个浏览器。
编辑:
const {Cluster} = require('puppeteer-cluster');
const puppeteer = require('puppeteer');
(async () => {
process.setMaxListeners(5);
const cluster = await Cluster.launch({maxConcurrency: 3});
let b = 15;
let d;
function myLoop() {
let g = 0;
for (g; g <= n; g++) {
console.log(g);
myFunc();
}
return g;
}
d = myLoop();
console.log('d: ' + d);
if (d > 0)
myLoop();
async function myFunc() {
await cluster.execute(async () => {
let browser = await puppeteer.launch({headless: false});
await browser.close();
});
}
await cluster.idle();
await cluster.close();
})();发布于 2019-11-20 23:56:54
我认为问题可能是由let引起的,let只存在于当前的代码块中,试着做一个函数。差不多吧。
let i = 0; // page index
let n = 0; // number of pages
let c = 0; // category index
let nc = 0; // number of categorys
for(i = 0; i < n; i++)
{
for(c = 0; c < nc; c++)
{
postrequest(i,c)
}
}
postrequest(pageindex,categoryindex)
{
// Do your async call ...
}如果我没有抓住问题的要点,很抱歉....
https://stackoverflow.com/questions/58957989
复制相似问题