0
我的腳本只是收集頁面上的報告數量,然後轉到下一頁並執行相同的操作。我們的目標是獲取跨多個頁面的報告總數。解析多個網頁並統計總項目
修訂
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
你好。感謝您的答覆。我修改了代碼,並提供了用於分離open和evaluate的建議。我仍然無法弄清楚.thenOpen函數之外的新計數值。 newReportCount的日誌看起來像是在返回值之前執行的,所以這就是爲什麼我得到該對象?我想我需要某種回調,但是我怎麼實現這個功能呢? – JTu 2015-02-15 06:56:30
@JeffreyTu請仔細閱讀我的回答。你不能從'casper.thenOpen'返回一些東西,因爲它與所有其他的'then *'和'wait *'函數是異步的。你可能希望'newCount'將會是一個全局變量,所以你可以添加它? – 2015-02-15 09:37:19