javascript 找不到变量 - PhantomJS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15302928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can't find variable - PhantomJS
提问by Antoine
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".
经过数小时无果的搜索,我在这里发帖。PhantomJS 不允许我使用下面代码中的变量,运行我的脚本时出现错误消息“找不到变量”。
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 =)
谢谢=)
回答by Ariya Hidayat
There is an important piece of information in the Quick Starttutorial (in its Code Evaluationsection):
快速入门教程(在其代码评估部分)中有一条重要信息:
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.
要在网页上下文中评估 JavaScript 或 CoffeeScript 代码,请使用evaluate() 函数。执行是“沙盒化的”,代码无法访问其自身页面上下文之外的任何 JavaScript 对象和变量。一个对象可以从evaluate() 返回,但是它仅限于简单的对象并且不能包含函数或闭包。
The problem with your code is thus twofold:
因此,您的代码存在双重问题:
- Variable
elem
is initialized outside the web page context, it's not reachable from the secondevaluate
. - You return a non-simple object, i.e. a DOM element.
- 变量
elem
在网页上下文之外初始化,它不能从第二个evaluate
. - 您返回一个非简单对象,即 DOM 元素。
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.
这是一个很容易解决的问题,主要是通过正确设计代码以适应实际的“监禁”执行模型。请仔细阅读所有相关文档并探索大量包含的示例。