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

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.
 public void selectCSSDropDown(){
  Select catagoryDropDown = new Select(driver.findElement(By.className("fk-menu-selector")));
It will give you error somewhat like blow: 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
    public void selectCssDropDownUsingCSS() {
     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
    public void selectCssDropDownUsingJavaScript(){
     JavascriptExecutor js = (JavascriptExecutor) driver;
     js.executeScript("selectMItem('Cameras', 'cameras')");


Unknown said...

What is heightened privileges browsers?

Post a Comment