簡體   English   中英

獲取使用 chrome-remote-interface 發出的 API 請求的響應

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

我想使用 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**
      }
    });
  })();

在此處輸入圖像描述

您可以使用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'});
})();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM