2015-07-10 59 views
0

我試着用網頁的代碼,當我們按下keydown時,它的內容動態加載。 (如臉書)發送keydown事件在PhantomJS中不起作用

目標是獲得所有淨流量並將其打印到控制檯。

var page = require('webpage').create(), 
    system = require('system'), 
    address; 

if (system.args.length === 1) { 
    console.log('Usage: netlog.js <some URL>'); 
    phantom.exit(1); 
} else { 
    address = system.args[1]; 

    page.onLoadFinished  = function(req) { 
     console.log('requested: ' + JSON.stiringify(req, undefined, 4)); 

    }; 
    page.open(url, function() { 
     page.sendEvent('keypress', page.event.key.keydown); 
    }); 
    page.onResourceRequested = function (req) { 
     console.log('requested: ' + JSON.stringify(req, undefined, 4)); 
    }; 

    page.onResourceReceived = function (res) { 
     console.log('received: ' + JSON.stringify(res, undefined, 4)); 
    }; 


    page.open(address, function (status) { 
     if (status !== 'success') { 
      console.log('FAIL to load the address'); 
     } 
     phantom.exit(); 
    }); 

} 
+0

難道我的回答幫助?你有什麼問題嗎? –

+0

是的,答案幫助我感謝 – Med

回答

1

首先,PhantomJS是異步的。你同時打開兩頁。當第二頁page.open()第一頁的加載被中止時。這意味着您的page.sendEvent()調用永遠不會執行。

如果你想看到的事件是否是做什麼的,你需要讓頁面加載,並做一些動作後等待一點點,看看是否有請求:

if (system.args.length === 1) { 
    console.log('Usage: netlog.js <some URL>'); 
    phantom.exit(1); 
} else { 
    address = system.args[1]; 

    page.onResourceRequested = function (req) { 
     console.log('requested: ' + JSON.stringify(req, undefined, 4)); 
    }; 

    page.onResourceReceived = function (res) { 
     console.log('received: ' + JSON.stringify(res, undefined, 4)); 
    }; 


    page.open(address, function (status) { 
     if (status !== 'success') { 
      console.log('FAIL to load the address'); 
      phantom.exit(1); 
     } 

     page.sendEvent('keypress', page.event.key.keydown); 

     setTimeout(function(){ 
      phantom.exit(); 
     }, 1000); 
    }); 
}