簡體   English   中英

循環嵌套casper.js操作

[英]Nesting casper.js actions in a loop

我正在嘗試在一個while循環中嵌套casper.then()操作。 但是,該腳本似乎從未在這些casper.then()函數中執行代碼。

這是我的代碼

    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');
        });
      }
    });

我想念什么嗎?

casper.then在隊列中安排一個步驟,並且不會立即執行。 僅在上一步完成時執行。 由於父級casper.then包含的代碼本質上是while(true) ,因此它永遠不會完成。

您需要使用遞歸對其進行一些更改:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM