evaluate()官方文档的解释:
Signature: evaluate(Function fn[, arg1[, arg2[, ...]]])
Basically PhantomJS’ WebPage#evaluate equivalent. Evaluates an expression in the current page DOM context:
casper.evaluate(function(username, password) {
document.querySelector('#username').value = username;
document.querySelector('#password').value = password;
document.querySelector('#submit').click();
}, 'sheldon.cooper', 'b4z1ng4');
Note: For filling and submitting forms, rather use the fill() method.
Warning: The pre-1.0 way of passing arguments using an object has been kept for BC purpose, though it may
not work in some case; so you’re encouraged to use the method described above
Understanding evaluate()
The concept behind this method is probably the most difficult to understand when discovering CasperJS. As a
reminder, think of the evaluate() method as a gate between the CasperJS environment and the one of the
page you have opened; everytime you pass a closure to evaluate(), you’re entering the page and execute
code as if you were using the browser console.
evaluate()是在casperjs环境和你所打开的网页的桥梁,也就是你使用evaluate()是在操作你当前打开的DOM文档,是casperjs环境和DOM文档的一个交互,这就像你是在用浏览器的控制台控制html内容是一样一样的。
举官方的例子看一下:
casper.evaluate(function(username, password) {
document.querySelector('#username').value = username; //操作当前加载到浏览器中的DOM
document.querySelector('#password').value = password;
document.querySelector('#submit').click();
}, 'sheldon.cooper', 'b4z1ng4');
thenEvaluate() 官方解释:
Signature: thenEvaluate(Function fn[, arg1[, arg2[, ...]]])
Adds a new navigation step to perform code evaluation within the current retrieved page DOM:
// Querying for "Chuck Norris" on Google
casper.start('http://google.fr/').thenEvaluate(function(term) {
document.querySelector('input[name="q"]').setAttribute('value', term);
document.querySelector('form[name="f"]').submit();
}, 'Chuck Norris');
casper.run();
This method is a convenient shortcut for chaining then() and evaluate() calls.
从最后的解释可以看出来 thenEvaluate()方法是then()和evaluate()方法的结合。这里的thenEvaluate()是继承上一个步骤结束后才运行的,而evaluate()方法不用等到上一个步骤运行结束就可以运行的。
参考代码:
phantom.outputEncoding="GBK";
var casper=require('casper').create({
clientScripts:[
'jquery.js'
],
pageSettings:{
loadImages:false,
loadPlugins:false
},
logLevel: "info",
verbose: true
});
casper.start('http://www.baidu.com',function(){
//var a=document.getElementById('su');
});
casper.wait(2000,function(){
casper.evaluate(function(term) { //这里我使用的wait函数等待上一个步骤运行结束后再使用的evaluate函数 效果和直接使用thenEvaluate()是一样一样的
$("#su").attr("value",term);
}, 'CasperJS');
});
casper.wait(2000,function(){
this.capture('hehe1.png');
casper.echo(casper.getTitle());
});
casper.run();