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
navand save it in themenu. - Line 2: We find an element with the class
navand with the IDsubmenu1and then save it inhidden_submenu. - Line 4: We chain all the actions in this line. We use
ActionChains(driver)to refer to the class, then we usemove_to_element(menu)to move the cursor to the element saved inmenu. We useclick(hidden_submenu)to click on the element saved inhidden_submenu. At the end of the line, we useperform()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
navand save it inmenu. - Line 2: We find an element with the class
navand with the IDsubmenu1. Next, we save it inhidden_submenu. - Line 4: We create an
actionsobject. - 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.
Free Resources