Learn to Handle Mouse Hover in Selenium
Tags: selenium, handlemousehover, automationtesting, cloudtesting
Published: 2023-08-18 09:15:32

Mouse hover actions play a vital role in web automation testing, especially when dealing with interactive user interfaces. During [web automation](https://www.lambdatest.com/learning-hub/web-automation?utm_source=devto&utm_medium=organic&utm_campaign=aug_18&utm_term=ap&utm_content=learning_hub), you may encounter a situation where certain features or elements on the user interface only appear or respond when the user hovers the mouse over them. The hover effect is essential for providing interactive and dynamic website user experiences. You can hover over an element using the Actions Class of Selenium WebDriver API and its method. By doing so, you can automate the validation of hover-based functionalities and ensure that the web application behaves correctly when users interact with it.

In this article, we will explore the concept of mouse hover in [Selenium](https://www.lambdatest.com/selenium?utm_source=devto&utm_medium=organic&utm_campaign=aug_18&utm_term=ap&utm_content=webpage) and then discuss its importance in [automation testing](https://www.lambdatest.com/automation-testing?utm_source=devto&utm_medium=organic&utm_campaign=aug_18&utm_term=ap&utm_content=webpage). After that, we will delve into the technical aspects of how to implement it using [Selenium WebDriver](https://www.lambdatest.com/learning-hub/webdriver?utm_source=devto&utm_medium=organic&utm_campaign=aug_18&utm_term=ap&utm_content=learning_hub) followed by some best practices. We will use Python programming language to implement Mouse hover in Selenium.

***Perform browser testing on the most powerful*** [***automation testing platform***](https://www.lambdatest.com/automation-testing?utm_source=devto&utm_medium=organic&utm_campaign=aug_18&utm_term=ap&utm_content=webpage)***. Leverage LambdaTest automation testing for faster, reliable and scalable experience on cloud.***

### What is Mouse Hover in Selenium?

Mouse hover in Selenium means using Selenium WebDriver to simulate a mouse hover action on an element. This action triggers various UI effects, such as displaying tooltips, revealing hidden elements, or opening drop-down menus. Mouse hover in Selenium is important in automated testing as they help validate dynamic behaviors and hidden functionalities that may only become visible or accessible upon hovering over certain elements. By performing mouse hover actions in automation tests, testers can ensure the accuracy and reliability of web applications under test.

As you may see from the image attached below, the home page of Flipkart (as it looks while writing this blog), Electronics is one of the broad categories listed on this e-commerce website. It is only when you hover over this category or element it displays or renders the sub-category list on the [DOM](https://www.lambdatest.com/blog/document-object-model/?utm_source=devto&utm_medium=organic&utm_campaign=aug_18&utm_term=ap&utm_content=blog). Further, when you hover over the *Gaming* sub-category, it displays or renders the following list of items on the DOM.

![image](https://cdn-images-1.medium.com/max/800/0*471IPTM16GCIE4sp.png)

This kind of use case is part of a UI that interacts well with the user.

### Importance of Mouse Hover in Selenium

Mouse hover in Selenium is highly valuable for various scenarios in automation testing, as listed below:

* It allows testers to ensure that dropdown menus work properly when the mouse hovers over them and that all menu options are functional.
    
* Testers can also verify tooltips and information that appear when hovering over certain elements.
    
* Mouse hover in Selenium enables the validation of hidden or dynamic elements, making sure they become visible and interactive when the mouse hovers over specific areas.
    

### How to Perform Mouse Hover in Selenium?

To perform mouse hover in Selenium, we use the ***Actions*** Class from the Selenium WebDriver API. This Class provides various methods to simulate complex user interactions. By creating an instance of the Actions Class and using its method, you can move the mouse pointer to the desired element on the web page and trigger the hover effect.

Once the hover action is performed, you can further validate the web application’s behavior using assertions or other validation techniques. It ensures that the mouse hover interactions work as intended.

So, let’s first explore the ***Actions*** Class of Selenium WebDriver before we get into the practical example of implementing mouse hover in Selenium.

***In this article, let us learn about the*** [***test cases for banking Applications***](https://www.lambdatest.com/learning-hub/banking-application-testing-test-cases?utm_source=devto&utm_medium=organic&utm_campaign=aug_18&utm_term=ap&utm_content=learning_hub) ***that are used to test a banking application. Before that, let us understand the workings of the banking domain in brief.***

### Actions Class of Selenium WebDriver

The Actions Class in Selenium is part of the Selenium WebDriver API and can be found in the ***selenium.webdriver.common.action\_chains*** module. This class offers a range of methods that enable the simulation of complex user interactions, including Mouse Hover Action, Clicking, Double-clicking, Dragging, Releasing, Holding an element, and many more.

You don’t need to install any additional libraries or packages to use the Actions Class in Selenium. The Actions Class is bundled in the Selenium WebDriver API and comes pre-installed with Selenium binding.

You may consider watching the below video from our Youtube channel to learn in detail how to handle Actions class in Selenium.

{% youtube 6PRjK1FEsyM %}

Follow the below steps to use the Actions Class:

* Import the webdriver module from the Selenium package.
    
* Import the ActionChains Class from the selenium.webdriver.common.action\_chains module.
    

After importing, the code snippet looks like this.

```plaintext
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains 
```

![image](https://cdn-images-1.medium.com/max/800/0*FCrkdC6X0LOwasUx.png)

### Implementing Mouse Hover in Selenium

Let’s take an example to understand mouse hover in Selenium using the Actions Class.

We are going to use [automation demos](https://www.lambdatest.com/automation-demos?utm_source=devto&utm_medium=organic&utm_campaign=aug_18&utm_term=ap&utm_content=webpage), a demo website maintained by LambdaTest for illustrations.

To implement Mouse Hover in Selenium, we will use the Actions Class of Selenium WebDriver API.

In the following example, we demonstrate how to use Selenium to perform a hover action over the “**Resources**” element and wait for up to 5 seconds and quit the browser session:

```plaintext
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import time

# Launch the Chrome browser
driver = webdriver.Chrome()

# Navigate to the website
driver.get("https://www.lambdatest.com/automation-demos")
driver.maximize_window()

# Locate the element to perform the hover action on
element_to_hover = driver.find_element(By.XPATH, '//*[@id="header"]/nav/div/div/div[2]/div/div/div[1]/div[3]/button')

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

# Perform the hover action
actions.move_to_element(element_to_hover).perform()
time.sleep(5)

# Close the browser
driver.quit()
```

As shown in the above example, we perform a mouse hover action over the **“Resources”** element and wait for 5 seconds and quit the browser.

![image](https://cdn-images-1.medium.com/max/800/0*55kXCWeWjtBLPTwA.png)

Let’s take another example where we automate the mouse hover action over an element and perform the ***click()*** action.

```plaintext
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import time

# Launch the Chrome browser
driver = webdriver.Chrome()

# Navigate to the website
driver.get("https://www.lambdatest.com/automation-demos")
driver.maximize_window()

# Locate the element to perform the hover action on
element_to_hover = driver.find_element(By.XPATH, '//*[@id="header"]/nav/div/div/div[2]/div/div/div[1]/div[3]/button')

element_to_hover1=driver.find_element(By.XPATH, '//*[@id="header"]/nav/div/div/div[2]/div/div/div[1]/div[3]/div/div/div/div[1]/div/div[1]/ul/li[3]/a/div[2]/h3')
# Create an instance of the ActionChains class
actions = ActionChains(driver)

# Perform the hover action
actions.move_to_element(element_to_hover).perform()
time.sleep(5)
actions.move_to_element(element_to_hover1).perform()
time.sleep(5)
actions.click(element_to_hover1).perform()
time.sleep(5)

# Close the browser
driver.quit()
```

As shown in the above example, we first hover over the **Resources** using their **XPath** and wait for 5 seconds, then we hover over **Learning Hub** and again wait for 5 seconds. After that, we perform the ***click()*** action on **Learning Hub** and again wait for 5 seconds.

![image](https://cdn-images-1.medium.com/max/800/0*aYlzgi-NIRh2MuRi.png)

![image](https://cdn-images-1.medium.com/max/800/0*kwg-0esdGphe2-n1.png)

![image](https://cdn-images-1.medium.com/max/800/0*R0F0BlW2qVTEucKI.png)

We have used the Actions Class from the Selenium WebDriver API. Now, let’s delve deeper into our comprehension by exploring the various methods and properties offered by the *Actions* Class in detail.

***Run your*** [***Selenium Automation***](https://www.lambdatest.com/selenium-automation?utm_source=devto&utm_medium=organic&utm_campaign=aug_18&utm_term=ap&utm_content=webpage) ***Testing scripts on the LambdaTest cloud grid. Test on 3000+ desktop & mobile environments. Try it for free.***

### Methods and Properties of Actions Class in Selenium

The [*Actions* Class in Selenium](https://www.lambdatest.com/blog/what-is-actions-class-in-selenium/?utm_source=devto&utm_medium=organic&utm_campaign=aug_18&utm_term=ap&utm_content=blog) has various methods and properties, which we will look at in this section with code examples.

#### move\_to\_element(WebElement element)

Moves the mouse cursor to the center of the specified web element.

Syntax:

```plaintext
actions.move_to_element(element)
```

![image](https://cdn-images-1.medium.com/max/800/0*7hzNNCJJvdjm8sh9.png)

Let’s understand this through an example.

```plaintext
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import time

# Launch the Chrome browser
driver = webdriver.Chrome()

# Navigate to the website
driver.get("https://www.lambdatest.com/automation-demos")
driver.maximize_window()
time.sleep(3)

# Locate the element to perform the hover action on
main_element = driver.find_element(By.XPATH, '//*[@id="header"]/nav/div/div/div[2]/div/div/div[1]/div[1]/div[1]/a')
sub_element = driver.find_element(By.XPATH, '//*[@id="header"]/nav/div/div/div[2]/div/div/div[1]/div[1]/div[2]/div[1]/div/div[1]/div/div[1]/ul/li[2]/a/div[2]/p')
# Create an instance of the ActionChains class
actions = ActionChains(driver)

# Build the mouse hover action with multiple actions using build()
actions = actions.move_to_element(main_element)
actions = actions.move_to_element(sub_element)

# Perform the built actions using perform()
actions.perform()

# Wait for a few seconds to observe any effects
time.sleep(5)

# Close the browser
driver.quit()
```

In the above example, we have used the ***move\_to\_element()*** method. Firstly, we hover over the **Platform** and then move to **Selenium Testing**, as shown below.

![image](https://cdn-images-1.medium.com/max/800/0*FSvLV986grTtWngD.png)

![image](https://cdn-images-1.medium.com/max/800/0*VsFDqqv1n1MWxKSt.png)

#### click(WebElement element):

Clicks the specified web element.

Syntax:

```plaintext
actions.click(element)
```

![image](https://cdn-images-1.medium.com/max/800/0*NYa48O2dKI33qwGb.png)

Let’s understand this through an example.

```plaintext
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import time

# Launch the Chrome browser
driver = webdriver.Chrome()

# Navigate to the website
driver.get("https://www.lambdatest.com/automation-demos")
driver.maximize_window()
time.sleep(3)

# Locate the element to perform the hover action on
main_element = driver.find_element(By.XPATH, '//*[@id="header"]/nav/div/div/div[2]/div/div/div[2]/a[2]')

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

# Build the mouse hover action with multiple actions using build()
actions = actions.click(main_element)

# Perform the built actions using perform()
actions.perform()

# Wait for a few seconds to observe any effects
time.sleep(5)

# Close the browser
driver.quit()
```

In the above example, we used the ***click()*** method where we first hover over the element **Sign Up** and then perform a ***click()*** action on it.

![image](https://cdn-images-1.medium.com/max/800/0*lNdsXXoyntRqROdO.png)

![image](https://cdn-images-1.medium.com/max/800/0*KRRpEF7cdfThq82I.png)

#### click\_and\_hold(WebElement element)

Clicks and holds the specified web element. This function also needs the ***release()*** method to get the desired functionality.

Syntax:

```plaintext
actions.click_and_hold(element)
```

![image](https://cdn-images-1.medium.com/max/800/0*AbPdG6FJuo2b7Cei.png)

#### release(WebElement element)

Releases the mouse button previously held on the specified web element.

Syntax:

```plaintext
actions.release(element)
```

![image](https://cdn-images-1.medium.com/max/800/0*DULUQAONtmvbnWD7.png)

Let’s take an example where we want to hover over an element (**Book a Demo**) and want to use ***click\_and\_hold()*** and ***release()*** methods.

```plaintext
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import time

# Launch the Chrome browser
driver = webdriver.Chrome()

# Navigate to the website
driver.get("https://www.lambdatest.com/automation-demos")
driver.maximize_window()

# Locate the "Resources" menu option to perform the hover action
Book_a_Demo = driver.find_element(By.XPATH, '//*[@id="header"]/nav/div/div/div[2]/div/div/div[2]/div[1]/button')

# Create an instance of the ActionChains class
actions = ActionChains(driver)
time.sleep(3)

# Perform the mouse hover action on the "Resources" menu option
actions.move_to_element(Book_a_Demo).perform()

# Click and hold the "Resources" menu option for 3 seconds
actions.click_and_hold().perform()
time.sleep(3)

# Release the click
actions.release().perform()

# Wait for a few seconds to observe any effects
time.sleep(5)

# Close the browser
driver.quit()
```

In the above example, we have performed a mouse hover over the “**Book a Demo**” element after 3 seconds of opening the page and used the **click\_and\_hold()** on the element for 3 seconds. Subsequently, we release the element using the ***release()*** method, maintaining the release for 5 seconds. This sequence of actions simulates user interaction and allows us to observe the effects on the “**Book a Demo**” element during the specified timeframes.

![image](https://cdn-images-1.medium.com/max/800/1*g-5VkmcPBvjyNPmRzwJSiw.png)

(You can see as we hover over the element “**Book A Demo**”, the border gets thicker.)

![image](https://cdn-images-1.medium.com/max/800/0*jnHtAqAFDiDetovq.png)

#### double\_click(WebElement element)

Performs a double-click action on the specified web element.

Syntax:

```plaintext
actions.double_click(element)
```

![image](https://cdn-images-1.medium.com/max/800/0*uUxYSqzzBpUScQDv.png)

Let’s understand this through an example.

```plaintext
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import time

# Launch the Chrome browser
driver = webdriver.Chrome()

# Navigate to the website
driver.get("https://www.lambdatest.com/selenium-playground/")
driver.maximize_window()
time.sleep(3)

# Locate the element to perform the hover action on
main_element = driver.find_element(By.XPATH, '//*[@id="__next"]/div/section[1]/div/h1')

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

# Build the mouse hover action with multiple actions using build()
actions = actions.double_click(main_element)

# Perform the built actions using perform()
actions.perform()

# Wait for a few seconds to observe any effects
time.sleep(5)

# Close the browser
driver.quit()
```

In the above example, we used the ***double\_click()*** method where we perform a double-click on the text **‘Playground’**, as you can see below.

![image](https://cdn-images-1.medium.com/max/800/0*bFfIcLWDkHoC7v-F.png)

![image](https://cdn-images-1.medium.com/max/800/0*bbqj4IgBN0boA9Cy.png)

***Run your*** [***Selenium online***](https://www.lambdatest.com/selenium-automation?utm_source=devto&utm_medium=organic&utm_campaign=aug_18&utm_term=ap&utm_content=webpage) ***Automation Testing scripts on the LambdaTest cloud grid. Test on 3000+ desktop & mobile environments. Try it for free.***

#### context\_click(WebElement element)

Performs a right-click (context-click) action on the specified web element.  
Syntax:

```plaintext
actions.context_click(element)
```

![image](https://cdn-images-1.medium.com/max/800/0*Z2AMl7yVZ6JHBHoE.png)

Let’s take an example to understand the **context\_click()** method.

```plaintext
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import time

# Launch the Chrome browser
driver = webdriver.Chrome()

# Navigate to the website
driver.get("https://www.lambdatest.com/automation-demos")
driver.maximize_window()

# Locate the "Resources" menu option to perform the hover action
context = driver.find_element(By.XPATH, '//*[@id="formcontent"]')

# Create an instance of the ActionChains class
actions = ActionChains(driver)
time.sleep(3)

# Perform the double click on the "Resources" menu option
actions.context_click(context).perform()

# Wait for a few seconds to observe any effects
time.sleep(5)

# Close the browser
driver.quit()
```

In the above program, we have performed the ***context\_click()*** method. This method is nothing, but it is just like a right-click. We automate the process of right-clicking through the Actions Class, as you can show in this example.

![image](https://cdn-images-1.medium.com/max/800/0*MYEopKU8TJO2ufMy.png)

#### drag\_and\_drop(WebElement source, WebElement target)

Drags the source element and drops it onto the target element.  
Syntax:

```plaintext
actions.drag_and_drop(source, target)
```

![image](https://cdn-images-1.medium.com/max/800/0*04lPGJFHH42U4QV5.png)

Let’s take an example to understand the **drag\_and\_drop()** method.

```plaintext
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import time

driver = webdriver.Chrome()
driver.get("https://jqueryui.com/droppable/")
driver.maximize_window()

driver.switch_to.frame(driver.find_element("class name", "demo-frame"))

# get the source and destination
source = driver.find_element(By.ID, "draggable")
destination = driver.find_element(By.ID, "droppable")

actions = ActionChains(driver)
time.sleep(2)

# drag_and_drop() method
actions.drag_and_drop(source, destination).perform()

# Wait for a few seconds to observe any effects
time.sleep(5)
driver.quit()
```

In the above program, we have performed the ***drag\_and\_drop()*** method. This method drags an element and drops it to the desired location. We automate the drag-and-drop process through the Actions Class, as shown in this example.

![image](https://cdn-images-1.medium.com/max/800/0*6vd6js45xp9lHfYl.png)

![image](https://cdn-images-1.medium.com/max/800/0*hD6yqVAndgFqawdE.png)

#### pause(long duration)

Pauses the execution for the specified duration in milliseconds.  
Syntax:

```plaintext
actions.pause(duration)
```

![image](https://cdn-images-1.medium.com/max/800/0*VximPRMc_Tjio0Vf.png)

Let’s take an example to understand the **pause()** method.

```plaintext
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import time

# Launch the Chrome browser
driver = webdriver.Chrome()

# Navigate to the website
driver.get("https://www.lambdatest.com/automation-demos")
driver.maximize_window()

# Locate the element to perform the hover action on
element = driver.find_element(By.XPATH, '//*[@id="footer"]/div[1]/div/div/div[2]/div/div[2]/ul/li[1]/a')

actions = ActionChains(driver)

# Perform the hover action
actions.move_to_element(element)

# Introduce a pause of 3 seconds
actions.pause(3)

# Click on the element after the pause
actions.click(element)

# Perform the built actions using perform()
actions.perform()

# Wait for a few seconds to observe any effects
time.sleep(5)

# Close the browser
driver.quit()
```

In this example, we first hover over the Blogs and pause for 3 seconds, then perform the ***click()*** action on it.

#### build()

Create complex actions or perform multiple actions sequentially.  
Syntax:

```plaintext
actions.build()
```

![image](https://cdn-images-1.medium.com/max/800/0*hVv-ucjSQvbO2UVM.png)

Let’s take an example to understand the **build()** method.

```plaintext
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import time

# Launch the Chrome browser
driver = webdriver.Chrome()

# Navigate to the website
driver.get("https://www.lambdatest.com/automation-demos")
driver.maximize_window()
time.sleep(3)

# Locate the element to perform the hover action on
main_element = driver.find_element(By.XPATH, '//*[@id="header"]/nav/div/div/div[2]/div/div/div[1]/div[3]/button')
sub_element = driver.find_element(By.XPATH, '//*[@id="header"]/nav/div/div/div[2]/div/div/div[1]/div[3]/div/div/div/div[1]/div/div[1]/ul/li[1]/a/div[2]/p')

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

# Build the mouse hover action with multiple actions using build()
hover_action = actions.move_to_element(main_element).move_to_element(sub_element).click(sub_element)

# Perform the built actions using perform()
hover_action.perform()

# Wait for a few seconds to observe any effects
time.sleep(5)

# Close the browser
driver.quit()
```

In the above example, we have used the ***build()*** method, which allows us to create a sequence of multiple actions more organized and concisely. This technique helps to perform complex interactions by chaining actions together. As shown in this example, we sequentially execute actions like ***move\_to\_element()*** and click() using the ***build()*** method.

First, we hover over the **Resources**. Then we hover over **Blog** using the ***move\_to\_element()*** method. At last, we performed the ***click()*** action. All the actions are performed sequentially

![image](https://cdn-images-1.medium.com/max/800/0*q3djtqVA7Jh1a_cL.png )

![image](https://cdn-images-1.medium.com/max/800/0*v93LJ3rb7cga9acO.png)

![image](https://cdn-images-1.medium.com/max/800/0*_vuHWdkZXH4GefpK.png )

#### perform():

Executes the sequence of actions defined using the **Actions Class**.  
Syntax:

```plaintext
actions.perform()
```

![image](https://cdn-images-1.medium.com/max/800/0*ur0KTxV6ohvtRXWt.png)

***Get started with this complete*** [***Selenium automation testing***](https://www.lambdatest.com/selenium?utm_source=devto&utm_medium=organic&utm_campaign=aug_18&utm_term=ap&utm_content=webpage) ***tutorial. Learn what Selenium is, its architecture, advantages and more for automated cross browser testing. Read more.***

### Best Practices for Mouse Hover Actions in Selenium

It is essential to follow some best practices while performing mouse hover actions in Selenium to ensure reliable and effective test automation. The following are some best practices for mouse hover actions in Selenium.

* **Use the Actions Class:** The Actions Class in Selenium provides a high-level interface for performing mouse and keyboard actions. It offers methods like ***move\_to\_element()***, ***click\_and\_hold()***, etc, that are specifically designed for mouse actions. You may use this class to perform mouse hover actions effectively.
    
* **Locate Elements Accurately:** To accurately locate the elements, you must use reliable and unique locators such as ID, Class, XPath, or CSS Selectors to identify the elements.
    
* **Use Explicit Waits:** In some cases, elements may become visible only after a certain action or delay. You can handle such dynamic elements by using explicit waits (**WebDriverWait**) and waiting for the element to be visible or clickable before performing the hover action.
    

For Example-

```plaintext
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Chrome()
driver.get("https://www.lambdatest.com/automation-demos")
driver.maximize_window()

wait = WebDriverWait(driver, 10)
element = wait.until(EC.visibility_of_element_located((By.XPATH, '//*[@id="__next"]/div[1]/section[1]/div')))
element1 = driver.find_element(By.XPATH, '//*[@id="header"]/nav/div/div/div[2]/div/div/div[1]/div[1]/div[1]/a')  
actions = ActionChains(driver)
actions.move_to_element(element1).perform()
time.sleep(5)

driver.quit()
```

In this example, we use Selenium WebDriver to perform a mouse hover in Selenium by using [explicit waits](https://www.lambdatest.com/blog/types-of-waits-in-selenium/?utm_source=devto&utm_medium=organic&utm_campaign=aug_18&utm_term=ap&utm_content=blog). After opening the website, we locate the element (**Selenium Playground**) using its [XPath](https://www.lambdatest.com/blog/complete-guide-for-using-xpath-in-selenium-with-examples/?utm_source=devto&utm_medium=organic&utm_campaign=aug_18&utm_term=ap&utm_content=blog) and wait for it for 10 seconds to become visible. Then, we find another element (**Platform**) to perform the hover action on it. After the hover action, we wait for 5 seconds to observe any effects.

This approach is particularly beneficial when dealing with dynamic elements that may take some time to load.

![image](https://cdn-images-1.medium.com/max/800/0*-rip6eCtxQDR9q2B.png)

![image](https://cdn-images-1.medium.com/max/800/0*I71VUIKtx2IO0n_S.png)

* **Validate the Hover Effect:** After performing the mouse hover action, verify that the expected changes or effects are reflected on the webpage. You can use assertions or other validation techniques to ensure the desired behavior.
    

Code Example:

```plaintext
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import time

class TestHoverEffect(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Chrome()
        self.driver.get("https://www.lambdatest.com/automation-demos")
        self.driver.maximize_window()

    def test_hover_effect(self):
        # Locate the element to perform the hover action on
        element_to_hover = self.driver.find_element(By.XPATH, '//*[@id="header"]/nav/div/div/div[2]/div/div/div[1]/div[3]/button')
        time.sleep(3)

        # Create an instance of the ActionChains class
        actions = ActionChains(self.driver)

        # Perform the hover action
        actions.move_to_element(element_to_hover).perform()

        # Wait for a few seconds to observe any effects
        time.sleep(3)

        # Validate the hover effect - Check if sub-menus becomes visible
        sub_menu = self.driver.find_element(By.XPATH, '//*[@id="header"]/nav/div/div/div[2]/div/div/div[1]/div[3]/div/div/div/div[1]/div/div[1]/ul')
        is_sub_menu_visible = sub_menu.is_displayed()

        # Print the result
        if is_sub_menu_visible:
            print("Sub-menu is visible after hover.")
        else:
            print("Sub-menu is not visible after hover.")


    def tearDown(self):
        self.driver.quit()

if __name__ == "__main__":
    unittest.main()
```

Output:

![image](https://cdn-images-1.medium.com/max/800/0*pBgZ2qjBcUhhmCb9.png)

We started by importing all the necessary modules from Selenium, including unittest, webdriver, By, ActionChains, and time.

![image](https://cdn-images-1.medium.com/max/800/0*KfusdIRw96GfjFSG.png)

In the **setUp** method, we first created a WebDriver instance (ChromeDriver in our case) is created. The script then navigates to the [automation-demos](https://www.lambdatest.com/automation-demos) website and maximizes the browser window.

![image](https://cdn-images-1.medium.com/max/800/0*aLMw7b9EXHDpjCLD.png)

In the **test\_hover\_effect** method, the element to perform the hover action on is located using its **XPath**, and a 3-second pause is introduced to ensure that the page is fully loaded before performing the action. The after we created an instance of the Actions class as actions.

The ***move\_to\_element(element\_to\_hover)*** method is called on actions to perform the mouse hover action on the specified element.

Another 3-second pause is introduced to observe any effects of the hover action.  
The sub-menu element is located using its XPath, and its visibility is checked using the ***is\_displayed()*** method. Based on the visibility of the sub-menu, the script prints whether the sub-menu is visible or not after the hover action.

![image](https://cdn-images-1.medium.com/max/800/0*1L4-9iBhxza31CpW.png)

The **tearDown** method closes the browser and ends the test.

![image](https://cdn-images-1.medium.com/max/800/0*K-MNQc0lXPo6CYYu.png)

The program uses the **Actions Class** to perform the hover action, then checks if the sub-menu is displayed using the ***is\_displayed()*** method. At last, we printed the result.

![image](https://cdn-images-1.medium.com/max/800/0*9-SbmZ9OAeLF87v2.png)

This helps validate the expected behavior of the hover effect on the dropdown menu during automation testing.

***Automate*** [***Cypress cloud***](https://www.lambdatest.com/cypress-testing?utm_source=devto&utm_medium=organic&utm_campaign=aug_18&utm_term=ap&utm_content=webpage) ***tests and perform browser automation testing with LambdaTest. Our cloud infrastructure has 3000+ desktop & mobile environments. Try for free.***

### Conclusion

This blog equipped you with the necessary knowledge to perform hover over an element or mouse hover using [Selenium Python](https://www.lambdatest.com/learning-hub/python-tutorial?utm_source=devto&utm_medium=organic&utm_campaign=aug_18&utm_term=ap&utm_content=learning_hub). We started by understanding the concept of mouse hover in Selenium and its significance in automation testing. Next, we delved into the Actions Class of Selenium WebDriver API, which plays a key role in achieving mouse hover actions, followed by practical examples.

After that, we explored the various methods and properties of the Actions Class through a detailed example. At last, we discussed essential best practices for executing mouse hover actions in Selenium.

If you would be interested in learning more about how to perform automated mouse and keyboard actions, consider checking out blogs on

1. [How To Perform Mouse Actions In Selenium WebDriver](https://www.lambdatest.com/blog/perform-mouse-actions-in-selenium-webdriver/?utm_source=devto&utm_medium=organic&utm_campaign=aug_18&utm_term=ap&utm_content=blog)
    
2. [Tutorial On Handling Keyboard Actions In Selenium WebDriver](https://www.lambdatest.com/blog/handling-keyboard-actions-in-selenium-webdriver/?utm_source=devto&utm_medium=organic&utm_campaign=aug_18&utm_term=ap&utm_content=blog)