gpt4 book ai didi

javascript - 找不到变量 - PhantomJS

转载 作者:可可西里 更新时间:2023-11-01 02:03:17 24 4
gpt4 key购买 nike

经过数小时的无果搜索后,我在这里发布。 PhantomJS 不允许我在下面的代码中使用变量,在运行我的脚本时出现错误消息“找不到变量”。

你知道我的问题在哪里吗?

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();

}

})

谢谢 =)

最佳答案

Quick Start中有一条重要信息教程(在其代码评估部分):

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.

因此,您的代码存在双重问题:

  1. 变量 elem 在网页上下文之外初始化,它无法从第二个 evaluate 访问。
  2. 您返回一个非简单对象,即 DOM 元素。

这是一个容易解决的问题,主要是通过适本地设计代码以适应实际的“监禁”执行模型。请仔细阅读所有相关文档并探索大量 included examples .

关于javascript - 找不到变量 - PhantomJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15302928/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com