如何

2016-10-18 62 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)); 
} 

});