+91 9790664230
kumar.arun211@gmail.com

Mouse Over actions using Python Selenium WebDriver

Blog to learn python and selenium

Mouse Over actions using Python Selenium WebDriver

There will be scenarios where we need to click on the item of a drop down menu.

In order to perform this action manually, first we need to bring up the drop down menu by holding mouse over the parent menu. Then click on required child menu from drop down menu displayed.

Using ActionChains class in Selenium WebDriver, we can do this step in same manner as we do manually.

Step 1:

Import webdriver module


from selenium import webdriver

ActionChains implementation is available in below package.


from selenium.webdriver.common.action_chains import ActionChains

Step 2:
Open Firefox browser and load URL.


driver = webdriver.Firefox(executable_path="");
driver.get("https://UrlToOpen");

Step 3:
Create ActionChains object by passing driver object


action = ActionChains(driver);

Step 4:
Find first level menu object in page and move cursor on this object using method ‘move_to_element()’.
Method perform() is used to execute the actions that we have built on action object. Do the same for all objects.


firstLevelMenu = driver.find_element_by_id("menu")
action.move_to_element(firstLevelMenu).perform();
secondLevelMenu = driver.find_element_by_xpath("//a[contains(text(),'menu1')]");
action.move_to_element(secondLevelMenu).perform();

Step 5:
Click on the required menu item using method click()


secondLevelMenu.click();

Final block of code:


	from selenium import webdriver
	from selenium.webdriver.common.action_chains import ActionChains
	
	driver = webdriver.Firefox(executable_path="");
	driver.get("https://UrlToOpen");
	
	action = ActionChains(driver);
	
	firstLevelMenu = driver.find_element_by_id("menu")
	action.move_to_element(firstLevelMenu).perform();
	
	secondLevelMenu = driver.find_element_by_xpath("//a[contains(text(),'menu1')]");
	secondLevelMenu.click();
	

Java code for the same operation:


	package com.allseleniumblog.sample;
	
	import org.openqa.selenium.By;
	import org.openqa.selenium.WebDriver;
	import org.openqa.selenium.firefox.FirefoxDriver;
	import org.openqa.selenium.interactions.Actions;
	import org.openqa.selenium.remote.DesiredCapabilities;

	public class MouseHover {
		public static void main(String[] args) throws InterruptedException {
			System.setProperty("webdriver.gecko.driver", "");
			DesiredCapabilities desiredCapabilities = DesiredCapabilities.firefox();
			WebDriver driver = new FirefoxDriver(desiredCapabilities);
			driver.get("https://UrlToOpen");
						
			Actions action = new Actions(driver);
			action.moveToElement(driver.findElement(By.id("menu"))).perform();
			
			driver.findElement(By.xpath("//a[contains(text(),'menu1')]")).click();
		}
	}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

© 2018 Copyrights. All Rights Reserved. Arunkumar Velusamy