我曾经截获了一些使用selenium向页面注入javascript的ajax调用.历史的不好的一面是,硒有时可能是,说“脆弱”.因此,无论如何我在进行注射时都会遇到硒异常.
无论如何,我的想法是拦截XHR调用,并将其响应设置为我创建的一个新的dom元素,我可以从selenium操作.在拦截的条件下,你甚至可以使用发出请求的url来拦截你真正想要的那个(self._url)
也许这有帮助.
browser.execute_script("""
(function(XHR) {
"use strict";
var element = document.createElement('div');
element.id = "interceptedResponse";
element.appendChild(document.createTextNode(""));
document.body.appendChild(element);
var open = XHR.prototype.open;
var send = XHR.prototype.send;
XHR.prototype.open = function(method, url, async, user, pass) {
this._url = url; // want to track the url requested
open.call(this, 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) {
oldOnReadyStateChange();
}
}
if(this.addEventListener) {
this.addEventListener("readystatechange", onReadyStateChange,
false);
} else {
oldOnReadyStateChange = this.onreadystatechange;
this.onreadystatechange = onReadyStateChange;
}
send.call(this, data);
}
})(XMLHttpRequest);
""")