如何

2016-10-18 63 views
1
頁面

上創建通過不同的行動CasperJS一個簡單的循環來我有此腳本如何

var i=0; 
casper.start('http://www.example.com'); 
casper.then(function() {  
    this.sendKeys('#search_field', i); 
    this.click('input.vtop') 
}); 

casper.then(function() { 
    description = this.fetchText('h2').trim(); 
    description_longue = this.fetchText('#parent-longtext-body').trim(); 
    price = this.fetchText("td.nowrap strong").trim(); 
})  

casper.then(function() { 
    this.capture('site'+'i'+'.png'); 
}); 

casper.viewport(1024, 768); 
casper.run(); 

我想我循環從0到5。我該怎麼辦呢? 簡單for(i=0;i<5;<++)不起作用!

+0

一個簡單的循環在CasperJS中工作得很好。它只是你想達到的目標。 –

回答

1

隨着each聲明:

casper.start().each(links, function(self, link) { 
    self.thenOpen(link, function() { 
     this.echo(this.getTitle()); 
    }) 
}) 

repeat

casper.start().repeat(5, function() { 
    this.echo("Badger"); 
}) 
1

環路工作完全正常。你只需要記住所有的then*wait*函數(以及其他一些函數)是異步的。您可以使用IIFE到迭代變量綁定到某個迭代:

casper.start(); 
casper.viewport(1024, 768); 

for(var i = 0; i < 5; i++){ 
    (function(i){ 
     casper.thenOpen('http://www.example.com'); 
     casper.then(function() {  
      this.sendKeys('#search_field', i); 
      this.click('input.vtop') 
     }); 

     casper.then(function() { 
      description = this.fetchText('h2').trim(); 
      description_longue = this.fetchText('#parent-longtext-body').trim(); 
      price = this.fetchText("td.nowrap strong").trim(); 
     })  

     casper.then(function() { 
      this.capture('site'+'i'+'.png'); 
     }); 
    })(i); 
} 

casper.run(); 

有關更多信息,請參見本:JavaScript closure inside loops – simple practical example

此外,casper.startcasper.run只能在腳本中出現一次。

0

你只需要把你所有的步驟放在一個函數中,這個函數需要我作爲參數。您可能還爲時過早捕捉的問題,所以這裏是一個簡單爲例添加.wait,希望它有助於:-)

casper.then(function() { 
for (i=0; i<6; i++) { 
    this.wait(1000, (function(j) { 
     return function() { 
      this.sendKeys('#YourId', 'number'+ j , {reset: true}); 
      this.capture("image"+j+".jpg"); 
     }; 
    })(i)); 
} 

});