Click On All 'a' Elements In Paragraph With Specific Class In Casperjs
I have the following problem. I have this structure of HTML code:
lorem ipsum, bla bla bla click<
Solution 1:
- You cannot use
document
andcasper
at the same time, becausedocument
is only available inside of the page context (casper.evaluate()
), butcasper
is not available in the page context. - You need to iterate over the clickable elements either fully in the page context or fully outside.
CSS selectors
casper.then(function(){
var numberOfElements = this.getElementsInfo("p.description").length;
for(var i = 1; i <= numberOfElements; i++) {
this.click("p:nth-child("+i+") a");
}
});
XPath expressions
It's possible to make this much more robust, by using XPath expressions, because they are much more expressive.
var x = require("casper").selectXPath;
...
casper.then(function(){
var numberOfElements = this.getElementsInfo("p.description").length;
for(var i = 1; i <= numberOfElements; i++) {
this.click(x("(//p[contains(@class,'description')])["+i+"])/a"));
}
});
where (//p[contains(@class,'description')])["+i+"])
means that a NodeList (//p[contains(@class,'description')]
) of p elements is built which all contain "description" as part of their "class" attribute. Then e.g. (nodeList)[3])
selects the third element from that list.
If you want to iterate inside of the page context, then you need to use a click function inside of the page context.
Post a Comment for "Click On All 'a' Elements In Paragraph With Specific Class In Casperjs"