How can I perform mouse hover action in Selenium-Python?


We can perform mouseover action in Selenium webdriver in Python by using the ActionChains class. We have to create an object of this class and then apply suitable methods on it.

In order to move the mouse to an element, we shall use the move_to_element method and pass the element locator as a parameter. Then apply the perform method to actually perform this action. After hovering on the element, we can apply click action on it with the help of the click method.

Syntax

a = ActionChains(driver)
m= driver.find_element_by_link_text("Enabled")
a.move_to_element(m).perform()

Let us try to hover on the element Enabled as shown on the below page −

Example

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://the-internet.herokuapp.com/jqueryui/menu#")
#object of ActionChains
a = ActionChains(driver)
#identify element
m = driver.find_element_by_link_text("Enabled")
#hover over element
a.move_to_element(m).perform()
#identify sub menu element
n = driver.find_element_by_link_text("Back to JQuery UI")
# hover over element and click
a.move_to_element(n).click().perform()
print("Page title: " + driver.title)
#close browser
driver.close()

Output

Updated on: 06-Apr-2021

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements