0

I'm trying to nest casper.then() actions in a while loop. However, It seems that the script never executes the code inside those casper.then() functions.

Here's my code

    casper.then(function() {
      while (this.exists(x('//a[text()="Page suivante"]'))) {

        this.then(function() {
          this.click(x('//a[text()="Page suivante"]'))
        });

        this.then(function() {          
          infos = this.evaluate(getInfos);
        });

        this.then(function() {
          infos.map(printFile);
          fs.write(myfile, "\n", 'a');
        });
      }
    });

Am I missing something ?

1 Answers1

0

casper.then schedules a step in the queue and doesn't execute immediately. It only executes when the previous step is finished. Since the parent casper.then contains code that is essentially while(true), it never finishes.

You need to change it a bit using recursion:

function schedule() {
  if (this.exists(x('//a[text()="Page suivante"]'))) {

    this.then(function() {
      this.click(x('//a[text()="Page suivante"]'))
    });

    this.then(function() {          
      infos = this.evaluate(getInfos);
    });

    this.then(function() {
      infos.map(printFile);
      fs.write(myfile, "\n", 'a');
    });

    this.then(schedule); // recursive step
  }
}

casper.start(url, schedule).run();
Artjom B.
  • 61,146
  • 24
  • 125
  • 222