Skip to main content

Selenium ActionChains using Python with examples

ActionChains are used to automate interactions like mouse movement, mouse button action, key press, context menu, drag and drop etc. These are typically complex operations which can't be performed directly with web driver elements.

Using ActionChains objects, specified actions are pushed into a queue and perform operation is called to execute these one by one.

Example 1 : Context Menu

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

CHROME_DRIVER = r"./browser_drivers/chromedriver"
driver = webdriver.Chrome(executable_path=CHROME_DRIVER)

driver.implicitly_wait(10)
driver.get("https://www.spicejet.com")
time.sleep(4)

# Initialize ActionChains Object
actionchains = ActionChains(driver)

login_element = driver.find_element(By.ID, "ctl00_HyperLinkLogin")
club_members_element = driver.find_element_by_xpath('//a[text()="SpiceClub Members"]')

actionchains.move_to_element(login_element)
actionchains.move_to_element(club_members_element)
actionchains.perform()

member_login_element = driver.find_element(By.LINK_TEXT, "Member Login")
member_login_element.click()


Example 2 : Drag and Drop

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

# Setup the driver
CHROME_DRIVER = r"./browser_drivers/chromedriver"
driver = webdriver.Chrome(executable_path=CHROME_DRIVER)

# Load the example website and maximize the window
driver.get("https://jqueryui.com/droppable/")
driver.maximize_window()

# Switch to frame holding our source / target elements
driver.switch_to.frame(0)

# Identify Source and Target elements
source = driver.find_element_by_id("draggable")
target = driver.find_element_by_id("droppable")

# Initialize ActionChains Object
actionchains = ActionChains(driver)

# Perform drag and drop
actionchains.drag_and_drop(source,target)
actionchains.perform()

# Close the driver
time.sleep(4)
driver.close()


Comments