CDP 过滤网络请求 - Puppteer

问题描述 投票:0回答:2

我正在尝试使用 Puppteer 获取特定网络请求的时间。

有没有办法在 Puppteer 中过滤来自 Chrome DevTools 协议的请求,以便仅在收到此特定网络响应时才会触发

responseReceived

我执行此任务的实际代码是:

const client = await page.target().createCDPSession();
await client.send('Network.enable');

// this method is deprecated and I don't know if it was the right thing to use ( https://chromedevtools.github.io/devtools-protocol/tot/Network#method-setRequestInterception )
await client.send('Network.setRequestInterception', {
    patterns: [
        {
            urlPattern: 'https://www.example.com/*task=customaction*',
            resourceType: 'XHR',
            interceptionStage: 'HeadersReceived'
        }
    ]
});

client.on('responseReceived', (requestId, loaderId, timestamp, type, response, frameId) => {
    console.log(`Debug data from: ${response.url} (${requestId})`)
    console.log('Timing:')
    console.log(response.timing)
    detach()
})

文档建议使用 Fetch 来替代

Network.setRequestInterception
(https://chromedevtools.github.io/devtools-protocol/tot/Fetch),但看起来 Fetch Domain 建议是修改网络请求。

javascript google-chrome-devtools puppeteer chrome-devtools-protocol
2个回答
0
投票

已经太晚了,希望你已经解决了这个问题。不过,发帖是为了让任何人都能受益。

您可以获取此处

所示的指标帮助

0
投票

要使用 Puppeteer 和 Chrome DevTools 协议 (CDP) 过滤网络请求并捕获特定请求的时间,您可以使用 Network.requestWillBeSent 和 Network.loadingFinished 事件而不是 responseReceived。这种方法允许您跟踪您感兴趣的特定请求并计算其时间。

const puppeteer = require('puppeteer');

async function captureNetworkTiming() {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  const client = await page.target().createCDPSession();

  await client.send('Network.enable');

  let requestId;
  let requestStartTime;

  client.on('Network.requestWillBeSent', (event) => {
    if (event.request.url.includes('https://www.example.com') && event.request.url.includes('task=customaction')) {
      requestId = event.requestId;
      requestStartTime = event.timestamp;
      console.log(`Request started: ${event.request.url}`);
    }
  });

  client.on('Network.loadingFinished', (event) => {
    if (event.requestId === requestId) {
      const duration = event.timestamp - requestStartTime;
      console.log(`Request completed. Duration: ${duration.toFixed(2)} ms`);
      console.log('Timing:', event.timing);
    }
  });

  await page.goto('https://www.example.com');

  // Wait for the specific request to complete
  await page.waitForResponse(
    (response) => response.url().includes('https://www.example.com') && response.url().includes('task=customaction')
  );

  await browser.close();
}

captureNetworkTiming();
© www.soinside.com 2019 - 2024. All rights reserved.