Learn Selenium

Sunday, November 29, 2015

Mouse hover function on DropDown menu & submenu selection in Selenium Webdriver

Mouse hover function on Dropdown Menu

In this post, discussing about how to do mouse hover to select dropdown menu and its submenu options.
  • Access the site http://www.hamaracoupons.in/
  • Mouse hover on the 'Categories' menu.

  • Inspect element on the menu by using firebug. Find the webelement.
<a class="color2" href="/all-categories">Categories</a>
  • To identify this webelement, we need xpath for this. Right click on the web element and inspect it by firepath. we can find an xpath like below:
  • Then xpath for the dropdown menu is html/body/div[2]/div/ul/li[3]/a.
WebElement mainMenu = driver.findElement(By.xpath("html/body/div[2]/div/ul/li[3]/a"));

We are going to use Actions Class for mouse operation.

                      Actions action = new Actions(driver);
                     action.moveToElement(mainMenu);
  • Inspect element on the submenu link 'All Categories' under 'Categories' section.
<a href="/all-categories">All Categories</a>
  • Then xpath for the submenu link is: html/body/div[2]/div/ul/li[3]/div/div[2]/a
WebElement subMenu = driver.findElement(By.xpath("html/body/div[2]/div/ul/li[3]/div/div[2]/a"));

action.moveToElement(subMenu).click().build().perform();

DropDownMouseOver.java


import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class DropDownMouseOver {

public static WebDriver driver = null;
public static void main(String[] args) throws InterruptedException {
driver = new FirefoxDriver();
driver.get("http://www.hamaracoupons.in/all-categories");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
Actions action = new Actions(driver);
WebElement mainMenu = driver.findElement(By.xpath("html/body/div[2]/div/ul/li[3]/a"));
action.moveToElement(mainMenu);
WebElement subMenu = driver.findElement(By.xpath("html/body/div[2]/div/ul/li[3]/div/div[2]/a"));
action.moveToElement(subMenu).click().build().perform();
driver.close();
}

3 comments:

  1. Hi,
    Thanks for the post.
    I tried your code in my project, but it didn't work. It was not clicking on subMenu link.

    My test scenarios:
    There is a main menu, where i have to either hover over/click, then i have to click on submenu link. which navigates to the new page.

    what i did to fix is:
    firstly did a perform action on mainMenu and then a click operation on subMenu link.

    Hope this help others, who lands on this page.

    Thanks,
    Neelima

    ReplyDelete
    Replies
    1. Thanks for the update Neelima. That worked for me.

      Delete
  2. This comment has been removed by the author.

    ReplyDelete