Selenium - ways to handle dropdown menus

Every web Page has at least one drop down menu bar, the bar may be horizontal or vertical.

Each item in the menu bar is a link corresponds to another page.

Menu bar have root items and in each root items we have one or more sub menus/items.

Actions on Root elements of a menu bar can be done as normal links, but sub elements are ( are hidden) only visible if we mouse hover to their corresponding root element,



as shown in above screenshot, to get the AntReporting item, we need to mouse hover on Selenium item.

Let's see code implementations to the above scenario...

public static void main(String[] args) throws InterruptedException { 
 WebDriver driver=new FirefoxDriver();
 driver.manage().deleteAllCookies();
 driver.manage().window().maximize();
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
 driver.get("http://www.qavalidation.com");
 
 WebElement Menu = driver.findElement(By.id("menu-bar"));
 WebElement root = Menu.findElement(By.linkText("Selenium"));
 //or, directly
 //WebElement root=driver.findElement(By.xpath(".//*[@id='menu-bar']/ul/li[2]/a"));
 //root.click(); //we can click this link as this is visible
 
 Actions A=new Actions(driver);
 A.moveToElement(root).build().perform();
 
 //WebElement sub=driver.findElement(By.xpath(".//*[@id='menu-bar']/ul/li[2]/ul/li[2]/a"));
 WebElement sub = Menu.findElement(By.linkText("ExcelRW"));
 //sub.click(); //throws error, as the link exist but not visible
 //to get the sub link visible, we need to expand the main element
 
 Thread.sleep(1000L); //wait is just to see how the mouse hovers on menu bar
 sub.click();
   }


Some scenarios, this above Action mouse hover doesn't work well, then we can use different approach like:

For each root or sub menu items, there is a url link associated, so instead of mouse hover directly use driver.get("link of the root/sub menu item");

Let's see how this works:

To click on the Selenium -> ExcelRW item, instead of mouse hover, we can use the url link associated with the ExcelRW item i.e- http://www.qavalidation.com/2015/03/selenium-excel-read-and-write-apachePOI.html



public static void main(String[] args) throws InterruptedException { 
    WebDriver driver=new FirefoxDriver();
    driver.manage().deleteAllCookies();
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    driver.get("http://www.qavalidation.com");
    Thread.sleep(1000);
    //click on sub menu item selenium -> ExcelRW
    driver.get("http://www.qavalidation.com/2015/03/selenium-excel-read-and-write-apachePOI.html");
}

No comments:

Post a Comment