Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

Selenium Python Webdriver Menu Test

In Selenium Python webdriver, you can use Action Chains to automate low level interactions such as mouse movements, mouse button actions, key press, and context menu interactions. Using Action Chains, you can do more complex actions like hover over and drag and drop.

When you call methods for actions on the ActionChains object, the actions are stored in a queue in the ActionChains object. When you call perform(), the events are fired in the order they are queued up.

In this example, you will learn how to use the method move_to_element(to_element)

move_to_element(to_element)

Moving the mouse to the middle of an element

Args: 

to_element: The WebElement to move to

Test Case

After moving mouse over to the menu item "Salzburg", verify that sub menu "Perch" should be displayed. 

Test Steps:

1. Open browser and navigate to the demo site "https://jqueryui.com/menu/"

2. Move mouse over to the menu item "Salzburg". 

3. Verify that sub menu "Perch" should be displayed

Test Script

 

Create a python file named "SeleniumPythonHoverOverMenu.py" and write the following code below. 

import unittest
import time
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains

class ActionChainsTests(unittest.TestCase):

    def setUp(self):
        #define a driver instance, for example Chrome
        self.driver = webdriver.Chrome()
        self.driver.maximize_window()

    def test_action_chains_hover_over_menu(self):
        driver = self.driver
        #navigate to the demo website
        driver.get('http://jqueryui.com/menu/')
        time.sleep(3)
        #define Frame
        frame=driver.find_element_by_tag_name('iframe')
        #Switch to the frame
        driver.switch_to_frame(frame)
        #define menu element
        menu_element=driver.find_element_by_id("ui-id-10")
        #define sub menu element
        sub_menu_element=driver.find_element_by_xpath("//ul/li[text()='Perch']")
        #define Action Chains
        action1=ActionChains(driver)
        action1.move_to_element(menu_element)
        action1.perform()
        #Sleep
        time.sleep(5)
        #verify that sub menu is displayed
        self.assertTrue(sub_menu_element.is_displayed())

    def tearDown(self):
        self.driver.close()
        self.driver.quit()
        
if __name__ == "__main__":
    unittest.main()

Run the script with command line and observe the result. The test passed as shown on the console output below.

C:\Python27>python SeleniumPythonHoverOverMenu.py
.
----------------------------------------------------------------------
Ran 1 test in 14.206s

OK