Drag and drop elements in selenium Python

In this article, we are going to learn how to Drag and drop elements in selenium Python. We will perform the drag and drop of a draggable element. We will make use of the Actionchains function from the selenium.webdriver module. We will use a website that will provide us with the droppable element and area to drop. This is only for learning purposes.

Environment & Requirements to drag and drop elements in selenium Python


How to Drag and drop element in selenium Python work


  • From the selenium module import webdriver, by module and actions module
  • Import time module also to wait for chrome at a given second.
  • Create a driver object which calls the browser
  • Webdriver. chrome Creates a new instance of the chrome driver. Starts the service and then creates new instance of chrome driver.
  • Now we pass the link of any site by using driver.get() method.
  • To go to a current tab I use the switch_to_frame method
  • Now I use two variable that store the element of drag and drop field.
  • After that, I used the drag and drop method and pass elements of the drag and drop field, and used perform a method that will perform drag and drop.
  • Now use time.sleep method to hold the driver in given time and then used closed method to close the browser.
//Program to Drag and drop elements in selenium Python  
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
import time
driver = webdriver.Chrome()
driver.maximize_window()
driver.get('https://jqueryui.com/droppable/')
driver.switch_to.frame(0)
source1 = driver.find_element(By.ID,'draggable')
target1 = driver.find_element(By.ID,'droppable')
actions2 = ActionChains(driver)
actions2.drag_and_drop(source1, target1).perform()
time.sleep(5)
driver.close()