Mouse Hover In Selenium Web Driver using action


Mouse Hover In Selenium

MoveToElement()

To achieve Mousehover in Selenium we use Actions class in Selenium WebDriver.
Step-1 Create object of an Actions Class by passing the WebDriver instance. With the object of the Actions class, driver moves to the main menu and then to the sub menu and click on it.

Mouse hover actions on an element using Actions Class:

Syntax-
WebElement ele = driver.findElement(By.xpath("xpath"));
Actions action = new Actions(driver);
action.moveToElement(ele).perform();

Selenium code For Hover the mouse
package automationtesting;


import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;


public class MouseHover {

       public static void main(String[] args) throws InterruptedException {
              // TODO Auto-generated method stub
              System.setProperty("webdriver.chrome.driver","D:\\Sandeep\\Soft\\chromedriver.exe");
              WebDriver driver= new ChromeDriver();
              driver.manage().window().maximize();
              driver.get("http://www.vnsgu.ac.in/");
               driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
             
              WebElement mainMenu = driver.findElement(By.className("parent"));
              Actions action = new Actions(driver);
              action.moveToElement(mainMenu).perform();

      
       }

}


Mouse hover actions on a sub-element using Actions Class

package automationtesting;


import java.util.concurrent.TimeUnit;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;


public class MouseHover {

       public static void main(String[] args) throws InterruptedException {
              // TODO Auto-generated method stub
              System.setProperty("webdriver.chrome.driver","D:\\Sandeep\\Soft\\chromedriver.exe");
              WebDriver driver= new ChromeDriver();
              driver.manage().window().maximize();
              driver.get("http://www.vnsgu.ac.in/");
               driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
              Actions action = new Actions(driver);
              WebElement mainMenu = driver.findElement(By.className("parent"));
              action.moveToElement(mainMenu).moveToElement(driver.findElement(By.xpath("/html/body/table/tbody/tr[1]/td/table/tbody/tr[2]/td/div/ul/li[2]/ul/li[6]/a"))).click().build().perform();
             

      
       }

}

Post a Comment

0 Comments