2017-03-17 40 views
0

我試圖在while循環中嵌套casper.then()動作。但是,似乎腳本從不執行casper.then()函數內部的代碼。在循環中嵌套casper.js動作

這裏是我的代碼

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

我這麼想嗎?

回答

0

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