获取使用 chrome-远程接口发出的 API 请求的响应

Get response of a API request made using chrome-remote-interface

我想使用 chrome-远程接口获取特定 API 调用的响应数据。 我不确定如何打印回复。我能够使用 GitHub 存储库中提供的演示代码获取正在调用的 APIs。

提到了我需要来自 Chrome DevTools 的屏幕截图。

  const chromeLauncher = require("chrome-launcher");
  const CDP = require("chrome-remote-interface");
  const axios = require("axios");

  (async function () {
    async function launchChrome() {
      return await chromeLauncher.launch({
        chromeFlags: ["--no-first-run", "--disable-gpu", "--no-sandbox"],
      });
    }

    const chrome = await launchChrome();
    const client = await CDP({
      port: chrome.port,
    });
    const { Network, Page } = client;
    await Page.enable();
    await Network.enable();
    await Page.navigate({ url: "https://clinique.com" });
    await Page.loadEventFired();

    Network.requestWillBeSent((params) => {
      if (
        params.request.url ===
        "https://www.clinique.com/rest/api/v1/ra/user?brand=2&region=0"
      )
      {
        **Want to get the response for the API**
      }
    });
  })();

您可以使用 Network.getResponseBody 来获取您想要的响应正文。请参阅这个最小的示例(我更改了目标 URL 因为您使用的那个没有立即获取,至少对我而言):

const chromeLauncher = require('chrome-launcher');
const CDP = require('chrome-remote-interface');

(async function () {
    const chrome = await chromeLauncher.launch({
        chromeFlags: ['--no-first-run', '--disable-gpu', '--no-sandbox'],
    });
    const client = await CDP({
        port: chrome.port,
    });

    const {Network, Page} = client;

    Network.responseReceived(async ({requestId, response}) => {
        if (response.url === 'https://geolocation.onetrust.com/cookieconsentpub/v1/geo/location') {
            const {body, base64Encoded} = await Network.getResponseBody({requestId});
            console.log(body, base64Encoded);
        }
    });

    await Network.enable();
    await Page.navigate({url: 'https://clinique.com'});
})();