Action chains in Selenium Python - Build an Automation Script
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # Setup WebDriver with webdriver.Chrome() as driver: driver.get('https://jqueryui.com/droppable/') # Switch to frame containing draggable and droppable WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, '.demo-frame'))) # Wait for draggable element draggable = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'draggable'))) droppable = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'droppable'))) # Perform drag and drop using ActionChains actions = ActionChains(driver) actions.drag_and_drop(draggable, droppable).perform() # Verify the text changed to 'Dropped!' dropped_text = droppable.text assert dropped_text == 'Dropped!', f"Expected text 'Dropped!' but got '{dropped_text}'" # No need to quit explicitly because of 'with' context
This script opens the jQuery UI droppable demo page, which contains draggable and droppable elements inside an iframe.
We first wait for the iframe to be available and switch to it, because the draggable and droppable elements are inside that frame.
Then we wait explicitly for both elements to be present using WebDriverWait and expected_conditions.
We use ActionChains to drag the draggable element and drop it onto the droppable element.
After performing the drag and drop, we check the text of the droppable element to confirm it changed to 'Dropped!'. This verifies the action was successful.
The use of explicit waits ensures the elements are ready before interaction, avoiding flaky tests.
The with statement ensures the browser closes automatically after the test.
Now add data-driven testing with 3 different draggable and droppable element pairs on the page