Count all elements inside iFrame with CasperJS
I am looking for a way to count each element inside a div. The problem is the div is inside the iFrame.
casper.then(function() {
this.echo(this.evaluate(function() {
__utils__.getElementByXPath('//*[@id="main-frame"]', __utils__.findAll('#design-scrollbox-0')).length;
}));
});
I am trying to do the following:
- Getting an iFrame with XPath
- Collecting each element
- and finally get the length of the returned array.
I would like if you could point me in the right direction. Unfortunately I cannot use jQuery version> 1.7, so jQuery.contents is not an option.
source to share
You can add some other version of jQuery, but you don't need it as CasperJS provides a convenient way to modify the iframe and render stuff in its context. casper.withFrame
is a shortcut to PhantomJS page.switchToChildFrame
and page.switchToParentFrame
. It creates a new step from the callback where additional steps can be nested.
Of course there are different types for counting items, but probably the easiest way is to use
casper.getElementsInfo(selector).length
This is the function to print the number of links I use for the proof of concept:
function printLinks(){
try{
this.echo("elements: " + this.getElementsInfo("a").length);
} catch(e) {
this.echo("CAUGHT: " + e);
}
}
Proof of concept for i frames:
casper.start("http://jsfiddle.net/anjw2gnr/1/")
.then(printLinks)
.withFrame(0, printLinks)
//.withFrame(1, printLinks)
.then(function() {
console.log('Done', this.getCurrentUrl());
})
.run();
prints
elements: 33 elements: 2
Proof of Concept for Frames:
casper.start("https://docs.oracle.com/javase/7/docs/api/index.html")
.then(printLinks)
.withFrame(0, printLinks)
.withFrame(1, printLinks)
.then(function() {
console.log('Done', this.getCurrentUrl());
})
.run();
prints
CAUGHT: CasperError: Cannot get information from a: no elements found. elements: 210 elements: 4024
So, if you want to count the elements but don't want to use a try-catch block, this is better:
casper.exists(selector) ? casper.getElementsInfo(selector).length : 0
source to share
You can use the CasperToChildFrame switch (see, for example, this link ) to get the "in" iframe.
(untested):
casper.then(function() {
// switch the context to first child frame
this.page.switchToChildFrame(0);
// ... execute casper commands in iframe context
// and switch back to parent frame if you need to
this.page.switchToParentFrame();
// ... execute casper commands in parent page context
});
To count the items you might try (untested):
casper.then(function() {
var amount_elements = this.evaluate(function() {
var elements = document.querySelectorAll("#design-scrollbox-0");
// you can store in the DOM:
window.amount_elements = elements.length;
// and return the amount
return elements.length;
});
});
// the object stored in the DOM can be used later on:
casper.then(function() {
var amount_elements = this.evaluate(function() {
return window.amount_elements;
});
});
source to share