Drag and Drop

Perform action by dragging an element from one place and dropping it at the required position.

By using TouchAction class objects we can perform the operation of Drag and Drop.

Below is the steps to perform Drag and Drop operation.

  • Create the object for TouchAction class
  • Create the Android Element variables of element to Drag and Element where to drop
  • Using the object of TouchAction class call the long press method and pass the drag element variable to it.
  • Now call the move_to() method and pass drop element variable
  • Finally call release() and perform() method to do the action.

Syntax :


actions = TouchAction(driver)
actions.long_press(drag_object).move_to(drop_object).release().perform()

Example: In the below example we are launching the app on an Android device and dragging the element from one place to another.

  • Launch the App on an Android device.
  • Click on the Drag and Drop button.
  • Create variables for drag variable and drop variable
  • Using the TouchAction object, call the long_press() method and move_to() method
  • Wait for 2 seconds
  • Close the App

DragAndDrop.py

from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
from selenium.common.exceptions import ElementNotVisibleException, ElementNotSelectableException, NoSuchElementException
from selenium.webdriver.support.wait import WebDriverWait
from appium.webdriver.common.appiumby import AppiumBy
import time

# Step 1 : Create "Desired Capabilities"
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['automationName'] = 'UiAutomator2'
desired_caps['platformVersion'] = '10'
desired_caps['deviceName'] = 'Pixel3XL'
desired_caps['app'] = ('/Skill2Lead/Appium_Demo_App/Android/Android_Appium_Demo.apk')
desired_caps['appPackage'] = 'com.skill2lead.appiumdemo'
desired_caps['appActivity'] = 'com.skill2lead.appiumdemo.MainActivity'

# Step 2 : Create "Driver object"
driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)

# Step 3 : Create "WebDriver object"
wait = WebDriverWait(driver, 25, poll_frequency=1,
                     ignored_exceptions=[ElementNotVisibleException, ElementNotSelectableException,
                                         NoSuchElementException])

# Step 4 : Scroll and click on "Drag and Drop" button
wait.until(lambda x: x.find_element(AppiumBy.ANDROID_UIAUTOMATOR,
    'new UiScrollable(new UiSelector()).scrollIntoView(text("DRAGANDDROP"))')).click()

# Step 5 : Create variables for drag variable and drop variable
ele_kw = wait.until(lambda x: x.find_element(AppiumBy.ID,"com.skill2lead.appiumdemo:id/ingvw"))
ele_lay = wait.until(lambda x: x.find_element(AppiumBy.ID,"com.skill2lead.appiumdemo:id/layout2"))

# Step 6 : Create TouchAction class object
actions = TouchAction(driver)

# Step 7 : Long press the element and drag it to required position
actions.long_press(ele_kw).move_to(ele_lay).release().perform()

time.sleep(2)

driver.quit()