Wednesday, September 15, 2010

Table walk through in WebDriver

Very Simple sample for dealing with table elements on webPage in WebDriver:


WebElement table = driver.findElement(By.name("meetingRoomTable"));
//findout all checkboxes within the table
List<WebElement> checkboxes = table.findElements(By.cssSelector("input[type=\"checkbox\"]"));
if (!checkboxes.isEmpty()){
for (WebElement checkbox : checkboxes){

if(!checkbox.isSelected()){
checkbox.toggle();
}
}
System.out.println("all checkboxes elements checked now");
}

else
System.out.println("no checkbox elements exsit on this table");

4 comments:

  1. Useful
    But i tend to use the xpath for locating elements
    :-)

    ReplyDelete
  2. @Jersy
    Xpath is powerful but should be your last choice.
    You had better to use id/name other than Xpath in most situations, mainly on 2 reasons:
    1> Efficient-- much slower for Xpath to locate an element
    2> Maintainable-- hard to understand from Xpath expression
    Here i use Css Selector to find an element is just for Demo purpose:)
    Xpath is your

    ReplyDelete
  3. @Cheng Chi
    Right~ it is hard to read~
    The only reason i use xpath is that i couldn't find another way to locate the element in tables
    like this:
    《tr》
    《td》《input type='checkbox'》《/td》
    《td》《a href='#'》...Automation...《/a》《/td》
    《/tr>》
    by that time i know nothing about cssSelector
    so i can only use
    "//a[contains(text(),‘Automation’)]/../..//input[@type='checkbox']"

    But i will try the CssSelector in the future

    ReplyDelete
  4. @Jersy
    Understood!
    Improve the Web Page's Testability. And tell your Project Manager what's your feeling as well :-)

    ReplyDelete