如何在 CasperJS 中创建一个简单的循环来循环执行页面上的不同操作

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

我有这个脚本

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;<++) 行不通!

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

一个循环工作得很好。您只需记住,所有 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 只能在脚本中出现一次。

您只需要将所有步骤放在一个以 i 为参数的函数中。您可能会遇到过早捕获的问题,所以这里有一个添加 .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));
}

});