How to handle mouse clicks and keyboard events using Selenium

Overview

Selenium provides us with the power to automate web browsers. Initially, Selenium was designed to automate web testing. However, we can utilize it to automate our daily administrative tasks.

Selenium allows us to do all the low-level interactions like mouse button actions, mouse movement, key press, and more. We utilize the ActionChains library to perform these operations.

The ActionChains library

The Actionchains library allows us to perform all the low-level tasks, such as mouse movement, mouse clicks, mouse hover, and sending keystrokes to elements. This library is also helpful for many other complex tasks, such as drag and drop.

Import ActionChains

The following example shows how we can import ActionChains into our code:

from selenium.webdriver.common.action_chains import ActionChains

Example

The ActionChains library can be used in two patterns:

  • Chained pattern
  • Queued pattern

Chained pattern

In a chained pattern, all the actions are connected in a single line, as shown below:

menu = driver.find_element(By.CSS_SELECTOR, ".nav")
hidden_submenu = driver.find_element(By.CSS_SELECTOR, ".nav #submenu1")
ActionChains(driver).move_to_element(menu).click(hidden_submenu).perform()

Code explanation

  • Line 1: We find an element with the class nav and save it in the menu.
  • Line 2: We find an element with the class nav and with the ID submenu1 and then save it in hidden_submenu.
  • Line 4: We chain all the actions in this line. We use ActionChains(driver) to refer to the class, then we use move_to_element(menu) to move the cursor to the element saved in menu. We use click(hidden_submenu) to click on the element saved in hidden_submenu. At the end of the line, we use perform() to perform all the chained actions.

Queued pattern

All the actions are queued in a pattern and then performed in the last line, as shown below:

menu = driver.find_element(By.CSS_SELECTOR, ".nav")
hidden_submenu = driver.find_element(By.CSS_SELECTOR, ".nav #submenu1")
actions = ActionChains(driver)
actions.move_to_element(menu)
actions.click(hidden_submenu)
actions.perform()

Code explanation

  • Line 1: We find an element with the class nav and save it in menu.
  • Line 2: We find an element with the class nav and with the ID submenu1. Next, we save it in hidden_submenu.
  • Line 4: We create an actions object.
  • Line 5: We add the task of moving the cursor to the element. Next, we it save in menu.
  • Line 6: We add the task of clicking on the element saved in hidden_submenu.
  • Line 7: We perform all the added tasks in the queue.

Copyright ©2024 Educative, Inc. All rights reserved