According to the CasperJS documentation, you can check to see if a selector exists
.
if (this.exists('#my_super_id')) {
this.echo('found #my_super_id', 'INFO');
}
You can put any CSS3 selector in place of #my_super_id
, and it works wonderfully. But, this isn't very useful if you want to click a specific button with a generic class.
<div class="btn button">Save</div>
The command clickLabel
works very well in these cases, but I have not found a way to check if a label exists before clicking it.
// This doesn't work, for obvious reasons
if (this.labelExists('Save')) {
this.clickLabel('Save');
}
Does anyone have a solution?
XPath is your friend (or you could iterate over all elements on the page).
var x = require("casper").selectXPath;
casper.labelExists = function(labelText, tag){
tag = tag | "*";
return this.exists(x("//"+tag+"[text()='"+labelText+"']"));
};
This creates a function on the casper
object that you can reuse and it works in exactly the same way as clickLabel
.