正在分析网站的多个页面并计算项目总数
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();
这是控制台中的输出
页码:3第一次计数:15[object Casper],当前位于文件:///**/reports.html32[object Casper],当前位于文件:///**/reports3.html
是的,这是可能的,但您使用的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循环还是迭代多个网页?
相关文章:
- 计算多个项目的价格
- JavaScript计算项目的总价
- 删除项目时的JavaScript计算
- Angularjs - 复选框 - 计算多个选定/未选定项目
- (角度.js)如何通过过滤器计算数组中有多少项目
- 正在分析网站的多个页面并计算项目总数
- 如何计算同一页面中项目的成本
- 使用Javascript计算特定项目的实例
- 循环 HTML 表并将相同的项目及其计算的金额添加到另一个表中
- 如何计算父路由模型的项目以在嵌套路由中使用它
- 计算数组中的重复项目
- 计算要填充 N 个项目的最大可用行和列数
- 在提交表格时计算所有动态项目的总数,包括复制的项目
- 计算输入到数组中的项目
- jQuery计算项目在可滚动窗口中的位置并滚动到它
- 尝试在考虑所选Javascript数量的情况下计算项目的总价
- 如何使用Protractor计算不可见项目
- JQuery:预先计算插入项目的高度
- 如何计算新项目在转换容器中的位置
- 如何计算项目中JS、CSS、LESS、HTML文件的代码行总数