Why complex interactions need Actions in Selenium Python - Automation Benefits in Action
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.action_chains import ActionChains # Setup WebDriver (assuming chromedriver is in PATH) driver = webdriver.Chrome() try: driver.get('https://jqueryui.com/droppable/') # Switch to frame containing draggable and droppable elements 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 droppable text changed to 'Dropped!' dropped_text = WebDriverWait(driver, 10).until( EC.text_to_be_present_in_element((By.ID, 'droppable'), 'Dropped!') ) assert dropped_text, "Droppable text did not change to 'Dropped!'" finally: driver.quit()
This script automates a drag and drop interaction on a webpage using Selenium with Python.
First, it opens the webpage and switches to the frame containing the draggable and droppable elements because these elements are inside an iframe.
It waits explicitly for the draggable and droppable elements to be present to avoid timing issues.
Then, it uses ActionChains to perform the drag and drop action, which is necessary for complex interactions that simple click or send keys cannot handle.
Finally, it verifies that the droppable element's text changes to 'Dropped!' to confirm the action succeeded.
The script uses explicit waits and proper locators for reliability and maintainability.
Now add data-driven testing with 3 different draggable and droppable element pairs on the page