Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
389 views
in Technique[技术] by (71.8m points)

javascript - Can't find variable - PhantomJS

I post here after many hours of fruitless searching. PhantomJS does not allow me to use a variable as in the code below, with the error message when running my script "Can not find variable".

Do you have any idea where can be my problem?

page.open(myurl, function (status) {

    if (status == 'success') {

        page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js", function() {

            elem = page.evaluate(function () {

                /* Select one element with jQuery */
                myElem = $('body');
                return myElem;

            })

            var elemHtml   = page.evaluate(function() { return $(elem).html(); });
            console.log(elemHtml);

        })

        phantom.exit();     

    }  

})

Thanks =)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is an important piece of information in the Quick Start tutorial (in its Code Evaluation section):

To evaluate JavaScript or CoffeeScript code in the context of the web page, use evaluate() function. The execution is "sandboxed", there is no way for the code to access any JavaScript objects and variables outside its own page context. An object can be returned from evaluate(), however it is limited to simple objects and can't contain functions or closures.

The problem with your code is thus twofold:

  1. Variable elem is initialized outside the web page context, it's not reachable from the second evaluate.
  2. You return a non-simple object, i.e. a DOM element.

This is an easy problem to solve, mainly by properly designing the code to fit the actual "jailed" execution model. Please carefully read all relevant documentation and explore tons of included examples.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...