2014-09-30 48 views
0

我正在編寫一個腳本,用戶可以通過該腳本從命令行下載Excel表格,而不是單擊內部網站上的「導出到Excel」按鈕。我的ExtJS用戶界面上已經有了一個'Export to Excel'按鈕,我想在腳本中重用這個功能。如何通過phantomjs點擊extjs按鈕後接收輸出

我可以加載頁面,並可以檢查Ext可用。我相信我需要撥打button.handler()來模擬點擊按鈕。事實上,它從螢火蟲中調用時下載了Excel表格。

我已經拿出這個到現在,使用phantomjs。基本上是loadspeed.jswaitfor.js的合併。

function waitFor(testFx, onReady, timeOutMillis) { 
    var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s 
     start = new Date().getTime(), 
     condition = false, 
     interval = setInterval(function() { 
      if ((new Date().getTime() - start < maxtimeOutMillis) && !condition) { 
       // If not time-out yet and condition not yet fulfilled 
       condition = (typeof(testFx) === "string" ? eval(testFx) : testFx()); //< defensive code 
      } else { 
       if(!condition) { 
        // If condition still not fulfilled (timeout but condition is 'false') 
        console.log("'waitFor()' timeout"); 
        phantom.exit(1); 
       } else { 
        // Condition fulfilled (timeout and/or condition is 'true') 
        console.log("'waitFor()' finished in " + (new Date().getTime() - start) + "ms."); 
        typeof(onReady) === "string" ? eval(onReady) : onReady(); //< Do what it's supposed to do once the condition is fulfilled 
        clearInterval(interval); //< Stop this interval 
       } 
      } 
     }, 250); //< repeat check every 250ms 
}; 

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

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

t = Date.now(); 
address = system.args[1]; 

page.open(address, function(status) { 
    if (status !== 'success') { 
     console.log('FAIL to load the address'); 
    } else { 
     t = Date.now() - t; 
     console.log('Loading time ' + t + ' msec'); 
     waitFor(function() { 
      var btn = page.evaluate(function() { 
       return Ext.getCmp('export_to_excel_btn'); 
      }); 
      return btn !== null; 
     }, 
     function() { 
      var xl; 
      waitFor(function() { 
       xl = page.evaluate(function() { 
        var btn = Ext.getCmp('export_to_excel_btn'); 
        return btn.handler(); // Never works. 
       }); 
       console.log(xl) 
       return xl !== null; 
      }, 
      function() { 
       console.log('In the inner waitFor'); 
       phantom.exit(); 
      }, 10000); 
     }, 10000); 
    } 
}); 

問題是內部的waitFor總是超時。任何想法如何解決這個問題?

回答

0

如果您只是點擊相應的按鈕,PhantomJS無法下載文件。您必須通過XMLHttpRequest顯式下載文件。要做到這一點,您必須對下載文件的JavaScript代碼進行反向工程。

function download(page, url) { 
    return page.evaluate(function(url){ 
     var xhr = new XMLHttpRequest(); 
     xhr.open("GET", url, false); 
     xhr.send(); 
     return xhr.responseText; 
    }, url); 
} 

即使你單擊該元素,然後試圖等待與page.onResourceRequested請求,然後觸發download與目前已知的網址,無法工作,因爲該請求沒有被PhantomJS發送。