Using ActionChains class in Selenium WebDriver, we can do this step in the same manner as we do manually.
Step 1:
Import webdriver module
from selenium import webdriver
ActionChains implementation is available in the 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 the first level menu object in page and move cursor on this object using the 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();
The 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();
}
}
If you are interested to learn Selenium on a much deeper level and want to become a professional in the testing domain, check out Intellipaat’s automation testing certification!