Monday, October 8, 2012

WebDriver - Selecting from CSS dropdown

In last few years the web designing has advanced too much. And for better look and feel people sometimes uses CSS to overwrite basic HTML component like editbox, dropdown, checkbox. It doesn't create any problem until you try to Automate it, but the moment you think to automate it started giving problem.
The biggest problem is, tools specifically selenium doesn't identify them as a proper element. For example, "All Categories" dropdown on flipcart.com.

If you will see it's code it is not standard HTML dropdown box, you wouldn't be able to find any select tag. And so the following code would fail.
@Test
 public void selectCSSDropDown(){
  driver.get("http://flipcart.com");
  Select catagoryDropDown = new Select(driver.findElement(By.className("fk-menu-selector")));
  catagoryDropDown.selectByVisibleText("Cameras");
 }
It will give you error somewhat like blow:
org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "a"
There are two workarounds to this.
  1. Click on the Dropdown and then click on the item you want to select 
     However using this you will be able to select by index only and not by visible text
    @Test
    public void selectCssDropDownUsingCSS() {
    
     driver.get("http://flipcart.com");
     driver.findElement(By.className("fk-menu-selector")).click();
     driver.findElement(By.cssSelector("div#fk-mI li:nth-child(5)")).click();
    
    }
  2. Through JavaScript
    You are lucky if your website if using JavaScript function to select an item, that way we can directly call those JavaScript functions as mention below
    @Test
    public void selectCssDropDownUsingJavaScript(){
     driver.get("http://flipcart.com");
     JavascriptExecutor js = (JavascriptExecutor) driver;
     js.executeScript("selectMItem('Cameras', 'cameras')");
    }

1 comments:

Unknown said...

What is heightened privileges browsers?

http://www.bestqtptraining.com/

Post a Comment