Selenium - Hover on an element


Hover on an Element in Selenium Python

To hover on an element in Selenium Python, you can use ActionChains class, which allows you to perform complex user interactions, such as moving the mouse.

Crate an ActionChains class instance, call move_to_element() on this ActionChains object, pass the element to hover on as argument, and then call the perform() action.

For example, if you would like to hover an a given element element_to_hover, you can use the following code.

# Create an instance of ActionChains
actions = ActionChains(driver)

# Move the mouse to the element to hover on
actions.move_to_element(element_to_hover).perform()

move_to_element() method makes the mouse pointer move to the given element.

Examples

In this example, we shall consider loading the HTML file at URL /tmp/selenium/index-33.html . The contents of this HTML file is given below.

<html>
<head>
<style>
    #msg:hover{
        color:blue;
    }
</style>
</head>
<body>
    <h2>Hello User!</h2>
    <p id="msg">This is my first paragraph. This is a sample text. Welcome!</p>
</body>
</html>

When a mouse hover action takes place for the paragraph element with id="msg", then the color of the paragraph changes to blue.

In the following program, we shall find the element with id="msg", and apply a hover action to that element. We have introduced some delay before and after the hover action, so that the effect of hover action can be seen.

Python Program (Selenium)

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
import time

# Setup chrome driver
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))

# Navigate to the url
driver.get('/tmp/selenium/index-33.html')

# Find the element
element_to_hover = driver.find_element(By.ID, 'msg')

# Create an instance of ActionChains
actions = ActionChains(driver)

# Optional
time.sleep(3)

# Move the mouse to the element to hover on
actions.move_to_element(element_to_hover).perform()

# Optional
time.sleep(3)

# Close the browser
driver.quit()

Summary

In this Python Selenium tutorial, we learned how to make hover action on an element, using ActionChains class in Selenium Python.