Capture AJAX response with selenium and python

I once intercepted some ajax calls injecting javascript to the page using selenium. The bad side of the history is that selenium could sometimes be, let’s say “fragile”. So for no reason I got selenium exceptions while doing this injection.

Anyway, my idea was intercept the XHR calls, and set its response to a new dom element created by me that I could manipulate from selenium. In the condition for the interception you can even use the url that made the request in order to just intercept the one that you actually want (self._url)

btw, I got the idea from intercept all ajax calls?

Maybe this helps.

(function(XHR) {
  "use strict";

  var element = document.createElement('div'); = "interceptedResponse";

  var open =;
  var send = XHR.prototype.send; = function(method, url, async, user, pass) {
    this._url = url; // want to track the url requested, method, url, async, user, pass);

  XHR.prototype.send = function(data) {
    var self = this;
    var oldOnReadyStateChange;
    var url = this._url;

    function onReadyStateChange() {
      if(self.status === 200 && self.readyState == 4 /* complete */) {
        document.getElementById("interceptedResponse").innerHTML +=
          '{"data":' + self.responseText + '}*****';
      if(oldOnReadyStateChange) {

    if(this.addEventListener) {
      this.addEventListener("readystatechange", onReadyStateChange,
    } else {
      oldOnReadyStateChange = this.onreadystatechange;
      this.onreadystatechange = onReadyStateChange;
    }, data);

Leave a Comment