Puppeteer / Nodejs,如何等待事件条件得到满足

时间:2018-10-10 05:13:11

标签: node.js puppeteer

我对nodejs还是很陌生,我正在使用puppeteer来自动进行一些浏览,但是由于某种场景的复杂性,我有点迷失了。

我单击一个按钮,它将搜索一些记录(使用ajax)并将结果放在页面上。

等待响应/请求确实不合适,因为我正在等待2-3个请求,具体取决于搜索类型-每个响应URL都完全相同。因此,我想我要等待3个特定URL的URL响应完成。

也许我需要重新考虑一下,或者我已经接近了?即使似乎增加了responseCount,promise也总是超时

    bundles.Add(new ScriptBundle("~/Script/js").Include(
              "~/Script/bootstrap-datepicker.js",
              "~/Script/bootstrap.min.js",
              "~/Script/custom-date-picker.js",
              "~/Script/custom-flex.js",
              "~/Script/custom-navigation.js",
              "~/Script/custom-owl.js",
              "~/Script/jquery.colorpanel.js",
              "~/Script/jquery.flexslider.js",
              "~/Script/jquery.min.js",
              "~/Script/owl.carousel.min.js"));

2 个答案:

答案 0 :(得分:0)

在收到每个响应后尝试检查条件。

async function intercepted(resp) {
  if (resp.url().includes('/ajaxpro/')) {
    return 1
  }
  return 0
}

let responseCount = 0
page.on('response', async resp => {
  let isTargetSearch = await intercepted(resp);
  responseCount += isTargetSearch;

  // - The current response is what we are looking for
  // - and reached 3 times.
  if(isTargetSearch && responseCount == 3) {
    // Do what you need to do here
  }
})

答案 1 :(得分:0)

也许您不必等到拦截了一定数量的响应后,再等到这些AJAX调用的结果在页面上呈现了 something (等待 visual < / strong>结果)。在这种情况下,您将进行page.waitForSelector(selector),其中选择器是调用结果在屏幕上呈现的信息。

与Puppeteer打交道时,我通常会发现等待可见结果会更好...