Select item from sub-menu of a menu using mouse over action in Selenium

SeleniumAutomation TestingTesting Tools

We can select an item from the sub-menu of a menu using mouse over action in Selenium webdriver with the help of the Actions class. We shall create an object of the Actions class and then apply moveToElement to it.

This method shall move the mouse to the middle of the menu which displays submenu on mouse over. Then apply the perform method to actually perform this action. After hovering on the menu, we shall select a sub-menu with the help of the click method.

Syntax

WebElement n=driver.findElement(By.id("nav-link-accountList"));
Actions a = new Actions(driver);
a.moveToElement(n).perform();

Let us hover on the below highlighted menu on the page and then select a submenu – Create a List −

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
public class SubMenuClick{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.amazon.com/");
      //identify menu
      WebElement n=driver.findElement(By.id("nav-link-accountList"));
      // object of Actions with method moveToElement
      Actions a = new Actions(driver);
      a.moveToElement(n).perform();
      //identify sub-menu element
      WebElement m=driver.
      findElement(By.xpath("//*[text()='Create a List']"));
      //move to element and click
      a.moveToElement(m).click().perform();
      System.out.println("Page navigated to: " +driver.getTitle());
      driver.quit();
   }
}

Output

raja
Published on 07-Apr-2021 08:09:13
Advertisements