简体   繁体   中英

Nesting casper.js actions in a loop

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 ?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM