How to drag and drop in Selenium WebDriver in Python

Selenium is a Python module that lets us automate browsers. We use it to test web applications by automating the actions performed on applications. In this Answer, we'll learn to drag and drop an element in Selenium.

We can drag and drop a DOMDocument Object Model element using the drag_and_drop() method provided by the ActionChains class.

Syntax

drag_and_drop(drag_from, drag_to).perform()

Parameters

The drag_and_drop method takes two parameters.

  1. drag_from: This specifies which element you want to drag from.

  2. drag_to: This specifies which element you want to drag to.

Let's take a look at an example of this.

Code example

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
 
options = Options()
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
prefs = {"download.default_directory": "."}
options.add_experimental_option("prefs", prefs)

#get instance of web driver
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)

time.sleep(1)

#open website
driver.get('https://jqueryui.com/droppable/')

#switch to frame where drag and drop is implemented
driver.switch_to.frame(driver.find_element("class name", "demo-frame"))

#get the source element
drag_from = driver.find_element("id", "draggable")

#get the target element
drag_to = driver.find_element("id", "droppable")

#ActionChains object
actions = ActionChains(driver)

time.sleep(2)

#drag and drop and element
actions.drag_and_drop(drag_from, drag_to).perform()

print("drag and drop is completed")
time.sleep(10)
Adding Selenium WebDriver in Python

Code explanation

In the above code snippet:

  • Line 15: We create an instance of Chrome WebDriver and assign it to the driver variable.

  • Line 20: We open the webpage using the get() method.

  • Line 23: We get the frame using its class name and switch to that frame using the switch_to() method.

  • Line 26: We get the source element that we want to drag and assign it to the drag_from variable.

  • Line 29: We get the target element to where we want to drop the source element and assign it to the drag_to variable.

  • Line 32: We create an instance of the ActionChains class and assign it to the actions variable.

  • Line 37: We drag and drop an element using the drag_and_drop() method which accepts the source element as the first and the target element as the second parameter. After that, we call the perform() method to perform the action.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved