Monday, August 16, 2010

Selenium methods for extracting elements

I have been working off late in automating web testing using the selenium framework. Not to mention there are handy generic methods to extract all links etc but sometimes one might need a bit more fine grained result than that. This post is some of the methods we implemented that extend to such functionality

We use TestNG and selenium java client driver for our tests, I am skipping the details of common helper methods session() that opens a link in selenium session, you can find it in the selenium-grid distribution. Here's a
method to check if all images present in the page are visible.
public void testAllImagesAreVisible() throws Exception {
 int nImages = Integer.parseInt(
session().getEval("window.document.images.length;"));
 LOGGER.debug("found images :::" + nImages);
 for (int i = 0; i < nImages; i++) {
   session().isVisible("dom=window.document.images[" + i + "]");
 }
}

the method finds the number of images in a page; and then lopps through them running the isVisible check. You might come across situations where you want to extract all links within a div; instead of the getAllLinks that does it for the entire page. Here's a way to do that.
public String[] getAllLinksWithinDiv(String divID){
 String domLocator = "dom=window.document.getElementById('"+
divID+"').getElementsByTagName('A')";
 ....
You can then store all link texts in a array for further use (clicking through all of them for example)
int nAnchors = Integer.parseInt(session().getEval(domLocator + ".length"))
String sArray[] = new String [nAnchors];
...
    sArray[i] = session().getEval(domLocator + "[" + i + "].text");
...

Thats about it.