2015-01-04 82 views
2

我有一個問題:我必須在java程序中執行一個phantomjs腳本,但我不能。 這是腳本的代碼:在java程序中執行phantomjs腳本

var page = require('webpage').create(); 
page.open('http://stackoverflow.com',function(status){ 
if(status !== 'success'){ 
    console.log('Open failed'); 
}else{ 
    console.log(page.evaluate(function(){ 
     return document.documentElement.outerHTML; 
    })); 
} 
phantom.exit(); 
}); 

在實踐中,我想執行一個網頁的JavaScript和之後採取的HTML結果。 我試着用這個鏈接Running Phantomjs from javascript, JSP or Java的代碼,但我的程序被阻止在該行

int exitStatus = process.waitFor(); 

我能做些什麼來解決這個?

謝謝

+0

您是否在類Unix操作系統下運行?你是否在/ usr/bin下安裝了PhantomJS和腳本? – 2015-01-04 10:58:03

+2

您的phantomjs腳本的輸出可能比Java的BufferedReader的緩衝區大小要長。因此,您可能會陷入您的phantomjs腳本阻止的陷阱,因爲您沒有讀取其輸出並且緩衝區已滿。檢查這個細節:http://stackoverflow.com/questions/5483830/process-waitfor-never-returns – Miichi 2015-01-04 11:11:48

+0

是的我在unix系統(Ubuntu),phantomjs安裝和腳本是在同一目錄。 – 2015-01-04 13:35:37

回答

0

您可以使用運行時類來執行終端命令。我能夠使用下面的程序生成我想要的輸出。

Runtime rt = Runtime.getRuntime(); 
    try{ 
     Process pr = rt.exec("pathToPhantomHome/phantomjs "+ " pathToJSfile"); 
     BufferedInputStream bis = new BufferedInputStream(pr.getInputStream()); 
     bis.close(); 
    }catch(Exception ex){ 
     ex.printStackTrace(); 
    }