找不到变量 - PhantomJS [英] Can't find variable - PhantomJS

查看:161
本文介绍了找不到变量 - PhantomJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过几个小时无果而终的搜索,我在这里发帖。 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();     

    }  

})

谢谢=)

推荐答案

有一个importa 快速入门教程中的一条信息(在其代码评估中)部分):

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


要在网页上下文中评估JavaScript或CoffeeScript代码,请使用evaluate()函数。执行是沙盒,代码无法访问其自身页面上下文之外的任何JavaScript对象和变量。可以从evaluate()返回一个对象,但它仅限于简单对象,不能包含函数或闭包。

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. 变量 elem 在网络外初始化页面上下文,它不能从第二个 evaluate 到达。

  2. 您返回一个非简单对象,即DOM元素。

  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.

这篇关于找不到变量 - PhantomJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆