2013-07-19 70 views
9

我目前使用Selenium Webdriver在頁面上進行一些驗證。 Webdriver由PhantomJS驅動。我知道在PhantomJS中,您可以使用以下示例收聽網絡:(從https://github.com/ariya/phantomjs/wiki/Network-Monitoring)。與Selenium Webdriver和Python一起使用PhantomJS

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嗎?

+0

如何,這是一個Python的問題嗎? – Marcin

+0

[建議的解決方案對我來說不起作用,但是這個可以工作(它使用driver.execute_script)](http://stackoverflow.com/a/36427562/1334996) – AlexMe

回答

0

什麼是你想在這裏實現?可以注入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}"); 
相關問題