运行 Puppeteer 实例中的一个循环

Running a loop within an instance of Puppeteer

刚开始使用 Puppeteer,我可以启动浏览器,执行 url、运行 一系列操作,然后关闭浏览器。我想看看我是否可以做的是打开浏览器并在同一会话中循环执行一组操作。

我有一个 JSON 对象,我想访问 urls,所以想遍历它

// teams.js
module.exports = {
  premier_league: [
    { team_name: "Team 1", url: "https://url-of-site/team_1"},
    { team_name: "Team 2", url: "https://url-of-site/team_2"}
  ]
}

我启动 puppeteer 的脚本如下

// index.js
const TEAM = require('./teams');
const puppeteer = require('puppeteer');

(async () => {
  // Initialise Browser
  const browser = await puppeteer.launch({headless: false});
  const page = await browser.newPage();
  await page.setViewport({
    width: 1280,
    height: 800
  });
  await page.goto('login page');

  await page.click('login_box');
  await page.keyboard.type('username');

  await page.click('login_password');
  await page.keyboard.type('password');

  await page.click('login_button');
  await page.waitForNavigation();

  // Go To Team URL
  await page.goto('Team URL')

  await browser.close();
})();

所以要遍历我的 JSON 对象,我可以使用

Object.keys(TEAM['premier_league']).forEach(function(key) {

  // Output url of each team
  console.log(TEAM['premier_league'][key]['url'])

});

如果我用我的循环将我转到 url,那么 page 将不再可访问

// index.js
const TEAM = require('./teams');
const puppeteer = require('puppeteer');

(async () => {
  // Initialise Browser
  const browser = await puppeteer.launch({headless: false});
  const page = await browser.newPage();
  await page.setViewport({
    width: 1280,
    height: 800
  });
  await page.goto('login page');

  await page.click('login_box');
  await page.keyboard.type('username');

  await page.click('login_password');
  await page.keyboard.type('password');

  await page.click('login_button');
  await page.waitForNavigation();

  Object.keys(TEAM['premier_league']).forEach(function(key) {

    // Go To Team URL
    await page.goto(TEAM['premier_league'][key]['url'])

  });

  await browser.close();
})();

实际错误是

await page.goto(TEAM[args][key]['url'])
    ^^^^

SyntaxError: Unexpected identifier

您的 Object.keys 回调函数也需要使用 async 才能在内部使用 await。尝试改变如下

Object.keys(TEAM['premier_league']).forEach( async function(key) {

    // Go To Team URL
    await page.goto(TEAM['premier_league'][key]['url'])

});

希望对您有所帮助