将 PhantomJS 与 Selenium Webdriver 和 Python 结合使用

Using PhantomJS with Selenium Webdriver and Python

提问人:Matt Stern 提问时间:7/20/2013 最后编辑:MarcinMatt Stern 更新时间:11/9/2013 访问量:2877

问:

我目前正在使用 Selenium Webdriver 对页面进行一些验证。Webdriver 由 PhantomJS 驱动。我知道在 PhantomJS 中,您可以使用如下所示的示例来监听网络:(来自 https://github.com/ariya/phantomjs/wiki/Network-Monitoring)。

var page = require('webpage').create();
page.onResourceRequested = function (request) {
    console.log('Request ' + JSON.stringify(request, undefined, 4));
};
page.onResourceReceived = function (response) {
    console.log('Receive ' + JSON.stringify(response, undefined, 4));
};
page.open(url);

如何在 Webdriver 中实现此功能?是否可以将函数绑定到 DesiredCapabilities?

JavaScript Selenium Web驱动程序 PhantomJS

评论

0赞 Marcin 9/19/2013
这怎么是一个 python 问题?
0赞 AlexMe 4/5/2016
提出的解决方案对我不起作用,但这个解决方案有效(它使用driver.execute_script)

答:

0赞 HerrWalter 11/9/2013 #1

你想在这里实现什么?可以注入 javascript。因此,你可以创建一个对象来侦听页面,并将其记录到一个对象中,稍后在执行某些操作时获取该对象。

试一试,但我不确定phantomJS是做什么的。

browser.execute_script("    
var requests= [];
var received = [];
var page = require('webpage').create();
page.onResourceRequested = function (request) {
    requests.push('Request ' + JSON.stringify(request, undefined, 4));
};
page.onResourceReceived = function (response) {
    received.push('Receive ' + JSON.stringify(response, undefined, 4));
};
page.open(url);");

稍后(如果您仍然在同一页面上)获取请求:

browser.execute_script("function(){return requests }()");

和接收到的连接:

browser.execute_script("function(){return received}");