1

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!

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
yarek
  • 11,278
  • 30
  • 120
  • 219

3 Answers3

1

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");
})
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
1

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.

Community
  • 1
  • 1
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
0

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

});

Steph Ane
  • 29
  • 5