With the advancements in web page design, a lot of new cool features have been added to the web pages, making it more and more easier for the users to interact with.
These rich web applications present a whole new level of different controls, that are implemented using JS libraries like JQuery.
And as such, these scenarios and controls present a whole new interesting challenge for testers to automate it.
One of the most useful controls that libraries like JQuery provide is to drag an element from one part of the screen to another part of the screen. You can pick an element, and drag it down from one corner to another, just like you would drag a person or a thing in real life.
A real time example, would be present in this link.
Today, we’re going to see how we’re going to automate, dragging an element, from one position to another position. Python API for Selenium provides a separate class called ActionChains
for this purpose. We need to create an object of this class and call the various methods that it provides us with, to interact with the elements. Let us see how.
__author__ = 'rahul' import unittest from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains class DragTest(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() def test_dragelement(self): driver = self.driver driver.maximize_window() driver.get('http://jqueryui.com/draggable/') driver.switch_to.frame(0) source1 = driver.find_element_by_id('draggable') action = ActionChains(driver) #move element by x,y coordinates on the screen action.drag_and_drop_by_offset(source1, 100, 100).perform() def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main()
See how the element is dragged from one position to another position
The ActionChains
class provides us with a method, drag_and_drop_by_offset(source,x-offset,y-offset)
to move/drag the element to desired x,y co-ordinates on the screen.
Now, what, if I don’t want to move by specific screen co-ordinates. Suppose I have a drag and drop situation, where an element is to be dragged and dropped on another web element. We have such an example here.
In that case, we would use a different method, provided by the same class : drag_and_drop(source,target)
Here’s how we would do it
source1 = driver.find_element_by_id('draggable') target1 = driver.find_element_by_id('droppable') actions2 = ActionChains(driver) actions2.drag_and_drop(source1, target1).perform() self.assertEqual("Dropped!", target1.text)
We find the source and destination elements (source is the one which is to be dropped in the target element).