I am attempting the following: parse a series of sequential URLs using CasperJS.
What I want to do in this example:
CasperJS should open "example.com/page-1.html", then "example.com/page-2.html", then "example.com/page-3.html".
My approach is to use a while
loop. The problem is that casper.thenOpen is running the while loop at a different "speed", and casper.thenOpen seems to execute after the loop has finished. See it for yourself:
var casper = require('casper').create({
pageSettings: {
webSecurityEnabled: false
}
});
casper.start();
casper.then(function() {
var current = 1;
var end = 3;
while(current <= end) {
casper.echo('casper.echo: '+current);
casper.thenOpen('http://example.com/page-' + current +'.html', function() {
this.echo('casper.thenOpen: '+current);
});
var current = current + 1;
} // end while
}); // end casper.then
casper.run(function() {
this.echo('Done.').exit();
});
The output:
casper.echo: 1
casper.echo: 2
casper.echo: 3
casper.thenOpen: 4
casper.thenOpen: 4
casper.thenOpen: 4
Done.
I don't understand the logic. The while
loop seems to run properly, since the "casper.echo" is counting correctly from 1 to 3. What bugs me is that the "casper.thenOpen" output is occurring after the loop is finished, since the value is 4.
In practical use, this code would open three times the page "example.com/page-4.html", instead of the ones we're expecting.
Why is this happening, and what would be the correct approach?