简体   繁体   中英

How to create a simple loop in CasperJS to loop through different actions on a page

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!

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

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.

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

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM