CasperJS provides the exists()
function. So, you can rewrite your code like this:
for (var i=1; i <=200; i++) {
(function(i){
casper.wait(6000, function() {
var button = x('//*[@id="mArticle"]/div[2]/a['+i+']');
if (!this.exists(button)) {
this.echo(i + " not available");
return; // the following `thenClick()` is not executed
}
this.thenClick(button, function (){
console.log('Searching dic');
words = words.concat(this.evaluate(getWords));
});
});
})(i);
}
I've also added an IIFE, so that you have the correct i
inside of the callback. For more information, see JavaScript closure inside loops – simple practical example.
This works, but it is not very efficient if one would assume that if link 100 is not there, then link 101 and 102 etc. are also not there. You would wait a lot (6 seconds times 100). In that case you need to do this recursively, because of the asynchronous nature of CasperJS:
function execOnce(casper, i, max){
// end condition
if (i === max) {
return;
}
casper.wait(6000, function() {
var button = x('//*[@id="mArticle"]/div[2]/a['+i+']');
if (!this.exists(button)) {
this.echo(i + " not available");
return;
}
this.thenClick(button, function (){
console.log('Searching dic');
words = words.concat(this.evaluate(getWords));
// recursive step
execOnce(this, i+1, max);
});
});
};
casper.start(url);
// start the recursive chain
casper.then(function(){
execOnce(this, 1, 200);
});
casper.run();
Note that now that you have it recursively, you can define a proper end condition by explicitly looking on the page what's there and what isn't.