2014-09-30 50 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发送。