[英]Node.js puppeteer - Use values from array in a loop to cycle through pages
I'm using node.js and puppeteer to get some data. 我正在使用node.js和puppeteer来获取一些数据。 ... now I want to visit different pages based on inregular values from an array: ...现在我想基于数组中的不规则值访问不同的页面:
My array looks like this: 我的数组如下所示:
rows = [ RowDataPacket {
id: 1,
value: 'L3',
name: 'Steve' },
RowDataPacket {
id: 2,
value: 'GU',
name: 'Peter' },
RowDataPacket {
id: 3,
value: 'M5',
name: 'John' }]
So the pages I want to visit are: 因此,我要访问的页面是:
await page.goto('url/search?action=getname&name=L3', {waitUntil: 'load'});
await page.goto('url/search?action=getname&name=GU', {waitUntil: 'load'});
await page.goto('url/search?action=getname&name=M5', {waitUntil: 'load'});
The array is actually 200 values long ... so I thought of doing a loop like this: 数组实际上是200个值长...所以我想到做这样的循环:
await page.goto('url', {waitUntil: 'load'});
rows = [ RowDataPacket {
id: 1,
value: 'L3',
name: 'Steve' },
RowDataPacket {
id: 2,
value: 'GU',
name: 'Peter' },
RowDataPacket {
id: 3,
value: 'M5',
name: 'John' }]
console.log(rows.length); // 3
for (let i=1; i < rows.length; i++){
await page.goto('url/search?action=getname&name='+value, {waitUntil: 'load'});
}
But how can I access the values ('value') from the array and use it in the loop accordingly? 但是,如何从数组访问值(“值”)并相应地在循环中使用它呢?
I would put the browser.newPage();
我会把browser.newPage();
inside the loop, like this: 在循环内部,如下所示:
const page = []
for (let i=1; i < rows.length; i++){
page[i] = await browser.newPage();
await page[i].goto('url/search?action='+rows[i].name+'&name='+rows[i].value, {waitUntil: 'load'});
}
Then, in the same or other for: 然后,以相同或其他方式进行:
const newPage = await page[i].evaluate(() => {
I'm not sure what's in the rows
array, as [ RowDataPacket {
is not valid JavaScript, but assuming that's a stand-in for the actual data, and each row has a value
property, you can use simpler syntax: 我不确定rows
数组中的内容,因为[ RowDataPacket {
不是有效的JavaScript,但是假设这是实际数据的替代,并且每行都有一个value
属性,则可以使用更简单的语法:
for (const row of rows) {
await page.goto(`url/search?action=getname&name=${row.value}`);
}
If you want to create a new page each time, per Emeeus's answer, you can wrap it in try
/ finally
: 如果您想每次创建一个新页面,根据Emeeus的回答,可以将其包装在try
/ finally
:
for (const row of rows) {
const page = await browser.newPage();
try {
await page.goto(`url/search?action=getname&name=${row.value}`);
} finally {
await page.close();
}
}
Notes: 笔记:
for...of
is the modern variant of a for
loop. for...of
是for
循环的现代变体。 waitUntil
defaults to load
, so you can leave it out. waitUntil
默认为load
,因此您waitUntil
它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.