0

I'm using PhantomJS to get some datas from WebSites and as a sample for my goal, I've made this:

var page=require('webpage').create();
page.open('http://www.phantomjs.org',function() {
    var my_data=page.evaluate(function() {
        var my_data=document.getElementsByTagName('h1').innerText;
        return my_data;
    });
    console.log(my_data);
    phantom.exit();
});

But this code is not working. Command prompt prints out only 'null'. What have I missed at here?

1 Answers1

1

This is because page.evaluate is async function. So console.log(my_data) is executed before page.evaluate finish, that's why you got null.

It is supposed to be

var page=require('webpage').create();
page.open('http://www.phantomjs.org',function() {
    page.evaluate(function() {
        var my_data=document.getElementsByTagName('h1').innerText;
        console.log(my_data);        
        phantom.exit();
    });    
});
deerawan
  • 8,002
  • 5
  • 42
  • 51