How do I get the response headers in Selenium?

Viewed 27148

How can I get request/response logs in selenium? I have an ajax call that returns login information, and whenever I try to capture it via:

 selenium.captureNetworkTraffic("json");

it returns only client-side items (like images .pn), but not the actual JSON response I'm interested in.

6 Answers

In case someone is still looking for an answer, there is a way to get the response headers using Selenium 4 and Chrome developer tools API

DevTools devTools = driver.getDevTools();
devTools.createSession();
devTools.send(Network.enable(Optional.empty(), Optional.empty(), Optional.empty()));
devTools.addListener(Network.responseReceived(),
        responseReceived -> {
            Headers headers = responseReceived.getResponse().getHeaders();
            if (!headers.isEmpty()){
                System.out.println("Headers:");
                headers.forEach((key,value) -> {
                    System.out.println("    " + key + "="+ value);
                });
            }
        });

This was tested using Selenium 4 alpha 6

If you are looking for other way round solution it could be also done using proxy server which will output log file including headers for each request/response which go through the proxy.

I have used Titanium Web Proxy and registered proxy for driver options like this:

ChromeOptions chromeOptions = new ChromeOptions
{
    Proxy = new Proxy
    {
        Kind = ProxyKind.Manual,
        HttpProxy = "localhost:8888"
    }
};
Related