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.
ActionChains
libraryThe 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.
ActionChains
The following example shows how we can import ActionChains
into our code:
from selenium.webdriver.common.action_chains import ActionChains
The ActionChains
library can be used in two patterns:
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()
nav
and save it in the menu
.nav
and with the ID submenu1
and then save it in hidden_submenu
.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.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()
nav
and save it in menu
.nav
and with the ID submenu1
. Next, we save it in hidden_submenu
.actions
object.menu
.hidden_submenu
.Free Resources