异步木偶浏览器断开连接几次迭代后

时间:2020-02-11 20:10:53

标签: javascript node.js puppeteer

我在很小的情况下用伪人测试了迭代。我已经读过伪造者断开连接的常见原因是Node script doesnt wait for the puppeteer actions to be ended。因此,我将代码段中的所有函数都转换为异步函数,但这并没有帮助。

如果具有六次迭代的小案例可以工作,我将在当前项目中以50次迭代的方式实现它。

'use strict';

const puppeteer = require('puppeteer');

const arrIDs = [8322072, 1016816, 9312604, 1727088, 9312599, 8477729];

const call = async () => {
    await puppeteer.launch().then(async (browser) => {
        arrIDs.forEach(async (id, index, arr) => {
            await browser.newPage().then(async (page) => {
                await page.goto(`http://somelink.com/${id}`).then(async () => {
                    await page.$eval('div.info > table > tbody', async (heading) => {
                        return heading.innerText;
                    }).then(async (result) => {
                        await browser.close();
                        console.log(result);
                    });
                });
            });
        });
    });
};

call();

3 个答案:

答案 0 :(得分:2)

forEach同步执行。用简单的for循环替换forEach

const arrIDs = [8322072, 1016816, 9312604, 1727088, 9312599, 8477729];
const page = await browser.newPage();

for (let id of arrIDs){
    await page.goto(`http://somelink.com/${id}`);
    let result = await page.$eval('div.info > table > tbody', heading => heading.innerText).catch(e => void e);
    console.log(result);
}

await browser.close()

答案 1 :(得分:1)

格式化和嵌套所有内容的方式似乎是回调地狱的化身。

这是我的建议,它不起作用,但是该结构对于Async / Await来说会更好地工作

const puppeteer = require("puppeteer");

const chromium_path_706915 =
  "706915/chrome.exe";

async function Run() {

    arrIDs.forEach(
        await Navigate();
    )
  async function Navigate(url) {
    const browser = await puppeteer.launch({
      executablePath: chromium_path_706915,
      args: ["--auto-open-devtools-for-tabs"],
      headless: false
    });

    const page = await browser.newPage();

    const response = await page.goto(url);

    const result = await page.$$eval("div.info > table > tbody", result =>
      result.map(ele2 => ({
        etd: ele2.innerText.trim()
      }))
    );


    await browser.close();
    console.log(result);
  }
}

run();

答案 2 :(得分:1)

除了其他答案,我想指出的是,异步和forEach循环并没有完全按照预期的方式播放。一种可能的解决方案是使用支持此功能的自定义实现:

实用功能:

async function asyncForEach(array: Array<any>, callback: any) {
  for (let index = 0; index < array.length; index++) {
    await callback(array[index], index, array);
  }
}

用法示例:

const start = async () => {
  await asyncForEach([1, 2, 3], async (num) => {
    await waitFor(50);
    console.log(num);
  });
  console.log('Done');
}

start();

通过塞巴斯蒂安·肖邦(Sebastien Chopin)的this article可以使事情变得更清楚,为什么异步/等待和forEach意外地动作。 Here it is as a gist