【问题标题】:How to tell CasperJS to loop through a series of pages如何告诉 CasperJS 循环浏览一系列页面
【发布时间】:2015-04-09 20:57:54
【问题描述】:

我尝试让 CasperJS 实现以下目标:

  • 浏览一系列按日期顺序命名的页面。
  • 在每一页上,找到一个 PDF 链接。
  • 下载 PDF。

我有一些工作代码,但我不明白 CasperJS 是如何处理事件序列的。

例如,在下面的代码示例中,CasperJS 尝试处理第 2 步,并抛出“ReferenceError: Can't find variable: formDate”,而第 1 步由于某种原因根本没有执行。

我的推理有什么问题?

在我看来,while 循环的执行速度与 casper.then 方法不同。

casper.start();

casper.thenOpen('http://www.example.com', function() {
    this.echo(this.getTitle());
});

casper.then(function() {

    var start = new Date('2013-01-01T00:00:00');
    var end = new Date('2013-01-31T00:00:00');

    while(start < end) {

          // step 1: define formDate  
          casper.then(function() {
            var formDate = start.getFullYear()+"-"+("0" + (start.getMonth() + 1)).slice(-2) +"-"+("0" + start.getDate()).slice(-2) ;
            casper.echo(formDate);

          });

          // Step 2: open the page and download the file
          casper.thenOpen('http://www.example.com/' + formDate, function() {

                        var url = this.getElementAttribute('div#pdffulllink a.pdf', 'href');
                        this.echo(url);
                        this.download(url, 'Downloaded_' + formDate + '.pdf');

          });

          casper.then(function() {
          // Step 3: redefine start
            var newDate = start.setDate(start.getDate() + 1);
            start = new Date(newDate);

          });

    }

});


casper.run(function() {
    this.echo('Done.').exit();
});

【问题讨论】:

    标签: javascript while-loop casperjs


    【解决方案1】:

    经过一番研究,我找到了解决这个问题的方法。

    问题是由于 casper.thenOpen 是一个 异步 进程,而其余的 javascript 是 同步

    我申请了an elegant method found in this thread(javascript for 循环中的异步进程)。

    按照该方法,下面是一个适用于 CasperJS 的示例:

    var casper = require('casper').create({
        pageSettings: {
            webSecurityEnabled: false
        }
    });
    
    casper.start();
    
    casper.then(function() {
        var current = 1;
        var end = 4;
    
        for (;current < end;) {
    
          (function(cntr) {
            casper.thenOpen('http://example.com/page-' + cntr +'.html', function() {
                  this.echo('casper.async: '+cntr);
                  // here we can download stuff
            });
          })(current);
    
          current++;
    
        }
    
    });
    
    casper.run(function() {
        this.echo('Done.').exit();
    });
    

    此示例将输出以下内容:

    casper.async: 1
    casper.async: 2
    casper.async: 3
    Done.
    

    循环正在工作! :)

    【讨论】:

    • 你会如何在这个循环中做一个“继续”等效项?
    猜你喜欢
    • 1970-01-01
    • 2010-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多