Frank Cunningham
Frank Cunningham

Reputation: 178

Execute phantomjs script in java program

I have a problem: I have to execute a phantomjs script in java program but I can't. this is the code of the script:

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();
});

In practice, I want to execute the javascript of a web page and after take the html resultant. I tried with the code at this link Running Phantomjs from javascript, JSP or Java but my program is blocked at this line

int exitStatus = process.waitFor();

what can I do to resolve this??

Thanks

Upvotes: 4

Views: 4196

Answers (1)

iCurious
iCurious

Reputation: 8313

You can use Runtime class to execute terminal commands. I was able to generate my desired output using below program.

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();
    }

Upvotes: 3

Related Questions