[英]Parsing multiple pages of website and count total items
我的腳本僅收集頁面上的報告數,然后轉到下一頁並執行相同的操作。 目的是獲得跨多個頁面的報告總數。
更新
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
是的,這是可能的,但是你用casper.thenOpenAndEvaluate()
其中有字then
在里面。 這意味着該函數是異步的,它返回casper
對象以啟用構建器/承諾模式。 因此,您無法從此類函數返回任何內容。 由於它是異步的,因此它將在當前步驟結束之后console.log(newCount);
之后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循環還是遍歷多個網頁?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.