Javascript 解析网站的多个页面并计算项目总数

Javascript 解析网站的多个页面并计算项目总数,javascript,casperjs,Javascript,Casperjs,我的脚本只是收集一页上的报告数量,然后转到下一页并执行相同的操作。目标是获取跨多个页面的报告总数 更新 这是控制台中的输出 Pages: 3 First count: 15 [object Casper], currently at file:///**/reports.html 32 [object Casper], currently at file:///**/reports3.html 是的,这是可能的,但是您使用casper.thenOpenAndEvaluate,其中包含单词then

我的脚本只是收集一页上的报告数量,然后转到下一页并执行相同的操作。目标是获取跨多个页面的报告总数

更新

这是控制台中的输出

Pages: 3 First count: 15 [object Casper], currently at file:///**/reports.html 32 [object Casper], currently at file:///**/reports3.html
是的,这是可能的,但是您使用casper.thenOpenAndEvaluate,其中包含单词then。这意味着该函数是异步的,它返回casper对象以启用builder/promise模式。所以不能从这样的函数中返回任何内容。由于它是异步的,因此将在当前步骤结束后执行,即在console.lognewCount;之后

您需要拆分函数,例如:

//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是异步的,您事先不知道需要打开多少页。我建议你看看这个问题,看一些例子:

你好。谢谢你的回复。我修改了代码,建议将open和evaluate分开。我仍然无法确定如何在.thenOpen函数之外设置新的计数值。newReportCount的日志看起来像是在返回值之前执行的,所以这就是我获取对象的原因?我想我需要某种回调,但我如何在casper中实现它?@JeffreyTu请仔细阅读我的答案。您无法从casper.thenOpen返回某些内容,因为它与所有其他then*和wait*函数一样是异步的。您可能希望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);
  });
}