Reputation: 12064
I have this script
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();
I want to loop i from 0 to 5. How do I do that?
simple for(i=0;i<5;<++)
does not work!
Upvotes: 1
Views: 899
Reputation: 29
You just need to put all your steps inside a function that takes i as parameter. You might have problems capturing too early, so here is a simple exemple adding .wait, hope it helps :-)
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));
}
});
Upvotes: 0
Reputation: 61952
A loop works perfectly fine. You simply have to keep in mind that all then*
and wait*
functions (as well as a few others) are asynchronous. You can use an IIFE to bind the iteration variable to a certain iteration:
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();
See this for more information: JavaScript closure inside loops – simple practical example
Also, casper.start
and casper.run
can only appear once in a script.
Upvotes: 1
Reputation: 185640
With the each statement :
casper.start().each(links, function(self, link) {
self.thenOpen(link, function() {
this.echo(this.getTitle());
})
})
or repeat
casper.start().repeat(5, function() {
this.echo("Badger");
})
Upvotes: 1