Javascript Dreaming.js-$未定义
我想在我的网页抓取中使用jquery和dream.js。基于,我可以只注入jquery并将文件复制到同一根文件夹。但不知怎的,我还是犯了一个错误: ReferenceError:$未定义 下面是我的代码:Javascript Dreaming.js-$未定义,javascript,jquery,nightmare,Javascript,Jquery,Nightmare,我想在我的网页抓取中使用jquery和dream.js。基于,我可以只注入jquery并将文件复制到同一根文件夹。但不知怎的,我还是犯了一个错误: ReferenceError:$未定义 下面是我的代码: var Nightmare = require('nightmare'); new Nightmare() .goto('http://google.com') .inject('js', 'jquery.min.js') .wait() .run(function(err,
var Nightmare = require('nightmare');
new Nightmare()
.goto('http://google.com')
.inject('js', 'jquery.min.js')
.wait()
.run(function(err, nightmare) {
if (err) {
console.log(err);
};
var items = [];
$('.someclass').each(function(){//<-- error - $ not defined
item = {};
item.value = $(this).val();
items.push(item);
});
console.log(items);
});
为了能够与页面及其变量交互,您需要使用: 使用arg1、arg2等调用页面上的fn .evaluate将fn的上下文更改为页面的上下文,以便可以像执行客户端代码一样执行fn,并可以访问窗口、文档、$和任何其他全局文件 另外,由于您提到了使用版本2.10,1.x版本中的.run函数已替换为,因此您需要使用.then和.catch分别处理成功和错误 对于您的代码片段:
new Nightmare()
.goto('http://google.com')
.inject('js', 'jquery.min.js')
.wait()
.evaluate(function() {
var items = [];
$('.someclass').each(function(){
item = {};
item.value = $(this).val();
items.push(item);
});
console.log(items);
})
.then(function () {
console.log('Done');
});
.catch(function (err) {
console.log('Error', err);
});
该项目的自述文件包括。Dream.js是无头的,没有html,我怎么能先包含jquery.js?npm列表显示我的版本是nightmare@2.10.0. 我相信我不确定评估是如何工作的。这个例子不是很有描述性。@soon我已经更新了我的答案,将重点放在v2.10上。