0

我想使用 chrome-remote-interface 获取特定 API 调用的响应数据。我不确定如何打印响应。我可以使用他们的 GitHub 存储库中提供的演示代码获取正在调用的 API。

提到了我需要来自 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**
      }
    });
  })();

在此处输入图像描述

4

1 回答 1

2

您可以使用它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'});
})();
于 2022-01-31T13:14:23.797 回答