0
0
Selenium Pythontesting~5 mins

Action chains in Selenium Python

Choose your learning style9 modes available
Introduction

Action chains let you do complex mouse and keyboard actions step-by-step. They help test things like drag-and-drop or hover effects.

You want to test dragging an item from one place to another on a webpage.
You need to hover over a menu to see a dropdown and click an option.
You want to simulate holding down a key while clicking.
You want to test double-click or right-click actions.
You need to move the mouse to a specific spot before clicking.
Syntax
Selenium Python
from selenium.webdriver import ActionChains

actions = ActionChains(driver)
actions.move_to_element(element).click().perform()

Always call perform() at the end to run the actions.

You can chain many actions before calling perform().

Examples
Move mouse to a button and click it.
Selenium Python
actions = ActionChains(driver)
actions.move_to_element(button).click().perform()
Drag an element from source to target and release the mouse.
Selenium Python
actions = ActionChains(driver)
actions.click_and_hold(source).move_to_element(target).release().perform()
Double-click on an element.
Selenium Python
actions = ActionChains(driver)
actions.double_click(element).perform()
Right-click (context click) on an element.
Selenium Python
actions = ActionChains(driver)
actions.context_click(element).perform()
Sample Program

This script opens a demo page, drags the blue box onto the gray box, and prints the text inside the target box after dropping. The text changes to "Dropped!" if successful.

Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
import time

# Setup driver (make sure chromedriver is in PATH)
driver = webdriver.Chrome()
driver.get('https://crossbrowsertesting.github.io/drag-and-drop.html')

# Find source and target elements
source = driver.find_element(By.ID, 'draggable')
target = driver.find_element(By.ID, 'droppable')

# Create action chain to drag and drop
actions = ActionChains(driver)
actions.click_and_hold(source).move_to_element(target).release().perform()

# Wait to see result
time.sleep(2)

# Check if drop was successful by text change
result_text = target.text
print(result_text)

driver.quit()
OutputSuccess
Important Notes

Action chains simulate real user actions step-by-step, so they are slower but more accurate than simple clicks.

Always import ActionChains from selenium.webdriver.

Use explicit waits if elements take time to appear before actions.

Summary

Action chains let you do complex mouse and keyboard actions in tests.

Chain multiple actions and call perform() to run them.

Useful for drag-and-drop, hover, double-click, and right-click tests.