如何使用 Puppeteer 获取请求的原始下载大小? [英] How can I get the raw download size of a request using Puppeteer?

查看:28
本文介绍了如何使用 Puppeteer 获取请求的原始下载大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即所有资源(包括视频/媒体)下载的数据总量,类似于 Chrome DevTools 的网络"选项卡返回的数据量.

That is, the total amount of data downloaded across all resources (including video/media), similar to that returned by Chrome DevTools' Network tab.

推荐答案

截至 2018 年 1 月,似乎没有任何方法可以适用于所有资源类型(监听 response 事件 视频失败),并且正确计算了压缩资源.

There doesn't seem to be any way to do this as of January 2018 that works with all resource types (listening for the response event fails for videos), and that correctly counts compressed resources.

最好的解决方法似乎是监听 Network.dataReceived 事件,并手动处理该事件:

The best workaround seems to be to listen for the Network.dataReceived event, and process the event manually:

const resources = {};
page._client.on('Network.dataReceived', (event) => {
  const request = page._networkManager._requestIdToRequest.get(
    event.requestId
  );
  if (request && request.url().startsWith('data:')) {
    return;
  }
  const url = request.url();
  // encodedDataLength is supposed to be the amount of data received
  // over the wire, but it's often 0, so just use dataLength for consistency.
  // https://chromedevtools.github.io/devtools-protocol/tot/Network/#event-dataReceived
  // const length = event.encodedDataLength > 0 ?
  //     event.encodedDataLength : event.dataLength;
  const length = event.dataLength;
  if (url in resources) {
    resources[url] += length;
  } else {
    resources[url] = length;
  }
});

// page.goto(...), etc.

// totalCompressedBytes is unavailable; see comment above
const totalUncompressedBytes = Object.values(resources).reduce((a, n) => a + n, 0);

这篇关于如何使用 Puppeteer 获取请求的原始下载大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆