Wednesday, April 13, 2011

Useful Selenium functions Part-1

Calculate similar links count:-
One of the major problems faced during automation is identifying objects on a page which have same attributes e.g multiple check-boxes with the same name and same id.

Number i = browser.getXpathCount("//a[starts-with(@filter,'B:')]");
System.out.println(i); // i will print count of filters starting with B: // this is used for comparing count

browser.click("xpath=(//input[@type='check-box'])[first()]"); // Select first checkbox
browser.click("xpath=(//input[@type='check-box'])[last()]"); // Select last checkbox

browser.click("xpath=(//input[@type='check-box'])[position()=2]"); // Select second checkbox
browser.click("xpath=(//input[@type='check-box'])[position()=4]"); // Select fourth checkbox

Similarly many button which is created using dynamic names can be accessed using the @start-with() function.
browser.click("xpath=button[starts-with(@id, 'li-')]"); // Click button name starting with li-**

Waitforpageload Failure:-

Sometimes waitForPageToLoad() fails then to handle this condition we just need to wait for an element we are waiting to load on the page. Once its loaded our execution should proceed. One of the most useful methods when working with selenium.
    int second = 0;
    // Text 'Copyright' to load on the present page.
    while(!selenium.isElementPresent("//div[@id='searchPageWrapper']/div[@id='footer']/div[contains(text(),'Copyright')]"))
       {
          if(second >= 5) // If page not loaded in 5 second break
                break;
          Thread.sleep(1000);
          second++;
        }

There are many more such methods that will be updated in the later parts.

No comments:

Post a Comment