Reading javascript variable from website using PhantomJS

后端 未结 2 1732
不知归路
不知归路 2020-12-07 02:40

I\'m new to Javascript and PhantomJS, but my seemly simple objective has proven to be harder to achieve than expected. I want to write a script that would load a website, an

相关标签:
2条回答
  • 2020-12-07 03:12

    Aaron's answer didn't work for me. Maybe it was valid back in 2013, but now (2016), it doesn't work anymore with the current version. In Aaron's example, foo returns a promise, not a value. console.log(foo) outputs Promise { <pending> }.

    Here's what I figured out :

    page
        .evaluate( function(){ return window.foo })
        .then ( function(foo){ console.log "foo = ", foo});
    

    Now you really get the value of foo.

    0 讨论(0)
  • 2020-12-07 03:22

    What you need to understand is that phantomJS has two JavaScript environments and those two are independent of each other. The inner one is the document script (which you have in any browser). The outer one is controlling what phantomJS should do. It simulates the user.

    So in a sense you need to tell phantomJS "the user opened the JavaScript console any typed ...". The evaluate command does this.

    So to read the value of the variable foo, you write this code:

    var foo = page.evaluate(function() {
        return document.foo;
    });
    

    Note: The document isn't strictly necessary but it helps to keep the two environments apart in the head of the developer.

    0 讨论(0)
提交回复
热议问题