Wednesday, 26 May 2010

A Selenium CaptureNetworkTraffic Example in Java

When I learned about Selenium’s ability to capture network traffic I was really excited. This opened up a whole new world of testing possibilities. I could capture the Ajax requests made to the server and check them for validity. When I visit pages I can check the web analytics messages sent back and check their correctness. So this post explains a little about how to use CaptureNetworkTraffic.

I found two blog posts useful when learning about capturenetworktraffic:
Corey has an open source tool which uses Selenium to provide some profiling stats for web visits.

If you would like to learn Selenium but have trouble following the examples here, then you might want to have a look at my book "Selenium Simplified" which provides a tutorial approach to learning Selenium using Java - no programming experience required.

A few months ago, I was looking for a proxy server that I could automate alongside my Selenium tests. I did a lot of web searches but found nothing suitable. And it never occurred to me that Selenium had this functionality out of the box until I found Corey’s post.
Basically, you start a Selenium session with:
  • selenium.start("captureNetworkTraffic=true");
And then, after a few requests you can get the dump of the html traffic as a string by issuing:
  • String trafficOutput = selenium.captureNetworkTraffic("json");
Simple. (you can use “xml”, “json” or “plain”)
I use the json format because when I returned it in xml some of the urls that returned were the wrong format. So in Java this means I use the gson library to parse json.

And when I run this conversion of Corey’s profiler I see the following output from visiting the homepage:
Warning you may get a concurrent modification exception reported when running the test. If this happens run it again. On some machines this happens more often than others and might seriously impact your ability to use this great function :(
results for
content size: 120617 kb
http requests: 22
status 200: 21
status 403: 1

file extensions: (count, size)
jpg: 4, 9.365000
png: 2, 1.969000
js: 4, 30.733000
ico: 1, 1.244000
unknown: 8, 53.546000
gif: 2, 16.319000
css: 1, 7.441000

http timing detail: (status, method, url, size(bytes), time(ms))
200, HEAD,, 0, 406
200, GET,, 30052, 641

To learn how to use this functionality you could read the source code to Corey’s tool, in Python. Or if you prefer Java you can follow the source below. I have done a quick, partial conversion of Corey’s tool in Java to illustrate how to use Gson and captureNetworkTraffic.

You can download the full source-code for this here.

Prerequisites to using this source-code:

  • You need to download Google-gson and add this lib to your project.

  • Also, since I have illustrated the basic principles in a @Test you will need to add either JUnit 4 or TestNG.

  • You also need to add selenium-server.jar to your project since we start Selenium automatically in this example

When you issue the selenium.captureNetworkTraffic(“json”) you receive a json string which has a collection of HTML Response Messages, e.g.

     statusCode: 200,
     method: 'HEAD',
     url: '',
     bytes: 0,
     start: '2010-05-26T13:33:37.048+0100',
     end: '2010-05-26T13:33:37.314+0100',
     timeInMillis: 266,
         name: 'Host',
         value: ''

When I parse this with gson

 Gson gson = new Gson();
 Type collectionOfHTMLRequestsType = 
              new TypeToken<collection><htmlrequestfromselenium>>(){}.getType();
 Collection<htmlrequestfromselenium> seleniumRequests = 
              gson.fromJson(trafficOutput, collectionOfHTMLRequestsType);

Gson will automatically build a collection of objects for me.

I created two objects to help with my Gson parsing:

 package com.eviltester.captureNetworkTraffic;

 import java.util.List;

 public class HTMLRequestFromSelenium {

  public int statusCode;
  public String method;
  public String url;
  public int bytes;
  public String start;
  public String end;
  public int timeInMillis;
  public List requestHeaders;


 package com.eviltester.captureNetworkTraffic;

 public class ValuePair {

  private String name;
  private String value;

Gson is well covered by the following articles

So this is my where the bulk of the work is done. Commented to explain the basics.

package com.eviltester.captureNetworkTraffic;

import static org.junit.Assert.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import org.junit.Test;
import org.openqa.selenium.server.SeleniumServer;
import com.thoughtworks.selenium.DefaultSelenium;

public class SeleniumTrafficAnalyserExampleTest {
 public void testProfileEvilTester() throws Exception{
  // Start the Selenium Server
  SeleniumServer srvr = new SeleniumServer();
  // Create a Selenium Session with captureNetworkTraffic ready
  String site = "";
  DefaultSelenium selenium = new DefaultSelenium("localhost", 4444, "*firefox", site);
  // open a page to get the traffic"/");
  // dump the traffic into a variable in Json format
  String trafficOutput = selenium.captureNetworkTraffic("json");

  // parse the json using Gson
  Gson gson = new Gson();
  Type collectionOfHTMLRequestsType = 
   new TypeToken<Collection<HTMLRequestFromSelenium>>(){}.getType();
  Collection<HTMLRequestFromSelenium> seleniumRequests = 
   gson.fromJson(trafficOutput, collectionOfHTMLRequestsType);
  // get ready to analyse the traffic
  TrafficAnalyser ta = new TrafficAnalyser(seleniumRequests);
  // this is pretty much copied from Corey's python example
  int num_requests = ta.get_num_requests(); 
  int total_size = ta.get_content_size(); 
  HashMap<Integer,Integer> status_map = ta.get_http_status_codes(); 
  HashMap<String, Object[]> file_extension_map = ta.get_file_extension_stats(); 
       System.out.println(String.format("results for %s",site)); 
       System.out.println(String.format("content size: %d kb",total_size)); 
       System.out.println(String.format("http requests: %d",num_requests));
       Iterator<Integer> statusIterator = status_map.keySet().iterator() ; 
       while ( statusIterator.hasNext (  )  )  
        int key =;
        System.out.println(String.format("status %d: %d", key, status_map.get(key)));
       System.out.println("\nfile extensions: (count, size)"); 
       Iterator<String> extensionIterator = file_extension_map.keySet().iterator() ; 
       while ( extensionIterator.hasNext (  )  )  
        String key =;
        System.out.println(String.format("%s: %d, %f", key,
      System.out.println("\nhttp timing detail: (status, method, url, size(bytes), time(ms))");
   for (Iterator iterator = seleniumRequests.iterator(); iterator.hasNext();) {
     HTMLRequestFromSelenium hr = (HTMLRequestFromSelenium);
     //totalContentSize += hr.bytes;
     System.out.println(String.format("%d, %s, %s, %d, %d",
      hr.statusCode, hr.method, hr.url, hr.bytes, hr.timeInMillis));
  // close everything down


Then the helper class

package com.eviltester.captureNetworkTraffic;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;

public class TrafficAnalyser {

 private Collection<HTMLRequestFromSelenium> seleniumRequests;
 public TrafficAnalyser(Collection<HTMLRequestFromSelenium> seleniumRequests) {
  this.seleniumRequests = seleniumRequests;

 public int get_num_requests() {
  return seleniumRequests.size();

 public int get_content_size() {
  int totalContentSize = 0;
  for (Iterator iterator = seleniumRequests.iterator(); iterator.hasNext();) {
   HTMLRequestFromSelenium hr = (HTMLRequestFromSelenium);
   totalContentSize += hr.bytes;
  return totalContentSize;

 public HashMap<Integer,Integer> get_http_status_codes() {
  HashMap<Integer,Integer> statusCodes = new HashMap<Integer,Integer>();
  for (Iterator iterator = seleniumRequests.iterator(); iterator.hasNext();) {
   HTMLRequestFromSelenium hr = (HTMLRequestFromSelenium);
    statusCodes.put(hr.statusCode, statusCodes.get(hr.statusCode)+1);
    statusCodes.put(hr.statusCode, 1);
  return statusCodes;

 public HashMap get_file_extension_stats() {
  HashMap<String,Object[]> extensions = new HashMap<String,Object[]>();
  for (Iterator iterator = seleniumRequests.iterator(); iterator.hasNext();) {
   HTMLRequestFromSelenium hr = (HTMLRequestFromSelenium);
   URL url = null;
   try {
    url = new URL(hr.url);
    String file_extension;
    double size = hr.bytes/1000.0;
    String doc = url.getPath();
     file_extension = doc.substring(doc.indexOf(".")+1).trim();

     file_extension = "unknown";
     Object[] stats = extensions.get(file_extension);
     stats[0] = (Integer)stats[0] +1;
     stats[1] = (Double)stats[1] + size;
     extensions.put(file_extension, stats);
     Object[] stats = new Object[2];
     stats[0] = 1;
     stats[1] = size;
     extensions.put(file_extension, stats);
   } catch (MalformedURLException e) {
  return extensions;


Hopefully this gives  a small overview of the capturenetworktraffic functionality in Selenium.

Related Reading:

If you would like to learn Selenium but have trouble following the examples here, then you might want to have a look at my book "Selenium Simplified" which provides a tutorial approach to learning Selenium using Java - no programming experience required.


  1. Ross Patterson27 May 2010 at 06:50

    FYI, the correct link for Corey Goldberg's article is

    Thanks Ross - a post written in haste as I jetted off on holiday - all fixed now.

  2. [...] • Evel Tester публикует практический пример работы с Selenium в Java. Задача: анализ сетевого трафика. [...]

  3. Awesome, that was really helpful... selenium should definitely implement/integrate those into a class or something.

    Thanks again,

  4. Thanks a lot for detailed explanation.

    I have modified "public List requestHeaders: to "public List requestHeaders" in HTMLRequestFromSelenium to make it work. Else, it was throwing exceptions.

  5. Sorry there was a type in my previous comment:
    modified “public List requestHeaders" to "public List requestHeaders"

  6. [...] [...]

  7. The explanation is as if I am being spoonfed :)

  8. That's me, Mr Spoon Feeder. :)

    Thanks for the comments Tarun.

  9. thank you for the article, worked like a charm.
    with maven it is even easier to handle gson dependency using:

  10. Thanks a million!! You saved my life :-)

  11. This worked flawlessly for me!

    package makemyhar;
    import java.util.ArrayList;
    import net.lightbody.bmp.BrowserMobProxy;
    import net.lightbody.bmp.BrowserMobProxyServer;
    import net.lightbody.bmp.core.har.Har;
    import net.lightbody.bmp.proxy.CaptureType;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.phantomjs.PhantomJSDriver;
    import org.openqa.selenium.phantomjs.PhantomJSDriverService;
    import org.openqa.selenium.remote.CapabilityType;
    import org.openqa.selenium.remote.DesiredCapabilities;

    public class MakeMyHAR {
    public static void main(String[] args) throws IOException, InterruptedException {

    BrowserMobProxy server = new BrowserMobProxyServer();
    server.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);

    ArrayList cliArgsCap = new ArrayList<>();

    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
    capabilities.setCapability(CapabilityType.SUPPORTS_JAVASCRIPT, true);
    capabilities.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, cliArgsCap);

    WebDriver driver = new PhantomJSDriver(capabilities);

    Har har = server.getHar();
    FileOutputStream fos = new FileOutputStream("C:\\HAR-Information.har");

    1. Great. Thanks for submitting the code.