6

我尝试使用 Selenium webdriver 捕获通常显示请求(方法类型、标题、参数)和响应的网络 XHR 日志(chrome 浏览器),但我只能获取客户端发送到服务器的 api 请求(不带参数),同时搜索我发现下面的代码,它只为我提供 api 请求:-

LogEntries logEntries = driver.manage().logs().get(LogType.BROWSER);
          for (LogEntry entry : logEntries) {
            System.out.println(new Date(entry.getTimestamp()) + " " + entry.getLevel() + " " + entry.getMessage())
}

但我还想获取客户端(浏览器)发送到服务器的所有参数以及响应。*相同的功能将如何用于 Firefox。

提前致谢!!

4

2 回答 2

3

您可以使用browsermobproxy

以下代码片段捕获所有请求和响应日志。

    // start the proxy
    BrowserMobProxy proxy = new BrowserMobProxyServer();
    proxy.start(0);

    // get the Selenium proxy object
    Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);

    // configure it as a desired capability
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);

    // start the browser up
    WebDriver driver = new FirefoxDriver(capabilities);

    // enable more detailed HAR capture, if desired (see CaptureType for the complete list)
    proxy.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);

    // create a new HAR with the label "yahoo.com"
    proxy.newHar("yahoo.com");

    // open yahoo.com
    driver.get("http://yahoo.com");

    // get the HAR data
    Har har = proxy.getHar();

任何 har 查看器都可以查看捕获的响应。

哈报告

于 2019-10-06T11:12:15.583 回答
0

如果您使用像 Axios 这样的库来进行 XHR 调用,您可以利用请求拦截器响应拦截器作为中间件来拦截并最终记录每个 XHR 调用及其响应,而无需依赖无头浏览器接口。

请求示例

client.interceptors.request.use(
  req => {
     // req contains your request data 
  },
  err => Promise.reject(err),
);

响应示例

client.interceptors.response.use(
  response => response, // XHR Response
  error => {
    const originalRequest = error.config; // Error.config contains too the original request
    // ...code
  })
于 2019-10-03T10:32:55.173 回答