2015-02-09 18 views
12

provo a fare CasperJS raggiungere i seguenti obiettivi:Come dire CasperJS a ciclo attraverso una serie di pagine

  • passare attraverso una serie di pagine che sono denominati in sequenza in base alla data.
  • In ogni pagina, individuare un collegamento PDF.
  • Scarica il PDF.

Ho ottenuto qualche codice funzionante, ma non capisco come CasperJS sta attraversando la sequenza di eventi.

Ad esempio, nell'esempio di codice riportato di seguito, CasperJS tenta di elaborare il passaggio 2 e genera un "ReferenceError: Can not find variable: formDate", mentre il passaggio 1 non viene eseguito affatto per qualche motivo.

Cosa c'è di sbagliato nel mio ragionamento?

Mi sembra che il ciclo while venga eseguito a una velocità diversa rispetto ai metodi 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(); 
}); 

risposta

17

Dopo alcune ricerche, ho trovato una soluzione a questo problema.

Il problema è causato da casper.thenOpen essendo asincrono processo , e il resto del JavaScript è sincrona.

Ho applicato an elegant method found in this thread (Processo asincrono all'interno di un javascript per ciclo).

seguito di tale metodo, qui è un esempio che funziona con 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(); 
}); 

Questo esempio uscita seguente:

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

Il circuito funziona! :)

+0

Come faresti un equivalente "continua" all'interno di questo ciclo? – ProGirlXOXO