如何在 CasperJS 中使用 jQuery?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17860928/
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
How Do I use jQuery in CasperJS?
提问by Michael Yaworski
casper.start(URL, function() {
casper.page.injectJs('C:/Users/Mike/Documents/n1k0-casperjs-bc0da16/jquery-1.10.2.min.js');
var names = $('span.author-name');
this.echo(names);
this.exit();
}
ReferenceError: Can't find variable: $
参考错误:找不到变量:$
What do I do? I've tried this too when creating the casper instance:
我该怎么办?我在创建 casper 实例时也试过这个:
var casper = require('casper').create({
// I've tried both commented lines below
// clientScripts: ['C:/Users/Mike/Documents/n1k0-casperjs-bc0da16/jquery-1.10.2.min.js']
// clientScripts: ['includes/jquery-1.10.2.min.js']
});
回答by jantimon
You have evaluate the jQuery code in the browser context using casper.evaluate
您已使用以下方法评估浏览器上下文中的 jQuery 代码 casper.evaluate
execute code as if you were using the browser console.
像使用浏览器控制台一样执行代码。
var nameCount = this.evaluate(function() {
var names = $('span.author-name')
return names.length;
});
this.echo(nameCount);
回答by mustapha mekhatria
Download the library then add its path using the clientScripts option:
下载库,然后使用 clientScripts 选项添加其路径:
var casper = require("casper").create({
clientScripts: [
'path/jquery-3.3.1.min.js'
]
});
And you are good to go with $(selector).
你很高兴使用 $(selector)。