大家好,

我想在一个页面中获得相同URL的所有响应,这样我就可以合并响应进行处理.

enter image description here

我试着用这个代码,它只给出第一个响应,但有10个相同的url请求data/api.json.

 const responsePromise = page.waitForResponse(response => {
      response.url().includes('data/api.json') && response.status() === 200
    });
    const response = await responsePromise;
    const data = await response.json()
    console.log(await response.allHeaders(), "allheader")

推荐答案

您可以使用page.on为您的请求分配处理程序.

您可以声明一个数组,然后在处理程序内部的Event requestfinished中将需要的请求推送到它,然后加载站点(或执行导致您的请求的操作),使用第一个请求的waitForResponse,当您预计所有请求都已收到时,等待某些条件(例如,对于请求收集长度不会随着某个时间间隔或网络空闲而变化).

    const responses: HTTPResponse[] = [];
    const urlPart = 'data/api.json';
    const handler = req => {
      if (req.url().includes(urlPart) && req.response() && req.response().ok()) {
        responses.push(req.response());
      }
    }
    page.on('requestfinished', handler);
    await page.goto("https://yourURL");
    await page.waitForResponse(res => res.request().url().includes(urlPart));
    // propbably there should be another condition where you are sure that no new responses are come
    const jsons = await Promise.all(responses.map(r => r.json()));
    jsons.forEach(json => console.log(json));

Node.js相关问答推荐

根据我的测试,为什么在编写Varint代码方面,NodeJS要比Rust快这么多?

如何修复PostgreSQL和NodeJS/NestJS应用程序之间的日期时间和时区问题?

类扩展值[object object]不是构造函数或null

Nestjs重写子类dto nodejs中的属性

如何使用包含条件正确分页的 sequelize 查询?

如何使用 node.js 将两个或多个 API 请求组合成一个端点并表达

npm install 在 Mac 上的 Node-gyp 构建错误

React Native:执行 com.android.build.gradle.internal.tasks.Workers$ActionFacade 时发生故障

使用正则表达式查找文档,但输入是数组

访问 Mongoose 查询之外的变量

nvm / node / npm: node 12 的 npm 比 node 14 的更新?

Puppeteer 错误:未下载 Chromium 修订版

使用 Socket.io 将客户端连接到服务器

如何在 node 中找到引用站点 URL?

有人在 NodeJS 中实现过 wiki 吗?

如何解决 Socket.io 404(未找到)错误?

Selenium WebDriver 等到元素显示

npm install - javascript堆内存不足

node.js 找不到模块mongodb

Npm postinstall 仅用于开发