我的脚本只是收集页面上的报告数量,然后转到下一页并执行相同的操作。目标是获得跨多个页面的报告总数。
已更新
var casper = require('casper').create({
clientScripts: ["./lib/jquery-2.1.3.min.js"],
// verbose: true,
logLevel: "debug"
});
casper.on('remote.message', function(msg) {
this.echo('LOG: ' + msg);
});
casper.on('page.error', function (msg, trace) {
this.echo( 'Error: ' + msg, 'ERROR' );
});
var reportCount, newReportCount, reportPages;
casper.start("reports.html", function() {
reportPages = this.evaluate(function() {
return $('#table2 tbody tr td').children('a').length -1;
});
//first page of reports
reportCount = this.evaluate(function() {
return $('#table1 tbody').first().children('tr').length;
});
this.echo('initial count: ' + reportCount);
this.echo('pages: ' + reportPages);
//check if more than 1 page and add report count
if (reportPages > 1) {
newReportCount = this.thenOpen('reports2.html', function(){
var newCount = this.evaluate(function(count) {
add = count + $('#table1 tbody').first().children('tr').length;
// console.log('new count inside: ' + add);
return add;
}, reportCount);
console.log(newCount); //this shows correct new value 32
});
console.log(newReportCount); //this shows [object Casper]
neoReportCount = this.thenOpen('reports3.html', function(count){
console.log(newReportCount); //this shows [object Casper]
//do the same count
}, newReportCount);
}
casper.run();
这是控制台中的输出
Pages: 3 First count: 15 [object Casper], currently at file:///**/reports.html 32 [object Casper], currently at file:///**/reports3.html
答案 0 :(得分:0)
是的,有可能,但您使用casper.thenOpenAndEvaluate()
,其中包含then
字样。这意味着此函数是异步的,它返回casper
对象以启用构建器/承诺模式。所以你不能从这样的函数返回任何东西。由于它是异步的,因此将在当前步骤结束后执行,即在console.log(newCount);
之后执行。
您需要拆分该功能,例如:
//check if more than 1 page and add report count
if (reportPages > 1) {
var newCount;
this.thenOpen('reports2.html', function(count){
newCount = this.evaluate(function(count){
add = count + $('#table1 tbody').first().children('tr').length;
console.log('new count inside: ' + add);
return add;
}, reportCount);
console.log(newCount);
}).thenOpen('reports3.html', function(count){
newCount += this.evaluate(function(count){
add = count + $('#table1 tbody').first().children('tr').length;
console.log('new count inside: ' + add);
return add;
}, reportCount);
console.log(newCount);
}).then(function(){
console.log(newCount);
});
}
好像你想要遍历多个页面。这通常是递归完成的,因为CasperJS是异步的,您事先并不知道需要打开多少页面。我建议你看看这个问题的一些例子:CasperJS loop or iterate through multiple web pages?