Selenium Course
- 62k Enrolled Learners
- Weekend/Weekday
- Live Class
Drag-and-drop is one of the core skills that an automation tester must have in Selenium. This technique helps the developer imitate user interactions with web elements. Such testing is applied to complex interfaces and dynamic web applications.
For this reason, it is very crucial to understand how this functionality could be implemented for practical testing. We will go through the different principles and how to drag and drop in Selenium with Python and Java, with respective practical working examples.
Drag and drop in Selenium is a technique for moving web elements around a web page from one position to another. It emulates an end-user action of clicking the web element, holding the mouse button, moving to a new position, and releasing the button. This functionality is exercised in almost every modern web application to perform different functions, like moving items around, file upload, and interactive UI components.
Selenium, using its class Actions, intrinsically supports a drag-and-drop operation. This class of Selenium supports different methods to perform complex actions, which users usually take part in; one of them is drag and drop. Generally, the process tends to have three significant steps bound together:
Drag and drop in Selenium, depending on the programming language one uses. For instance, drag and drop in Selenium Python would look quite different from Drag and drop in Selenium Java. However, the fundamental concept still holds across languages.
It is worth mentioning that how to perform drag-and-drop in selenium is susceptible and tricky to automate. They mainly require the correct timing and coordination between various mouse events. Moreover, some web applications specifically implement custom drag-and-drop behavior, which may not work with the earlier-mentioned standard methods that Selenium provides. In such cases, the JavaScript execution approach is necessary. If you want to learn more about how to handle drag and drop in Selenium, consider taking a Selenium Course or looking up resources on Selenium Tutorial.
While Drag and drop is a particular action, the Action Class in Selenium offers much more. Their differences may be further elaborated as below:
The Action Class is versatile and can be adjusted to create a series of custom actions. It can significantly help in more complex interactions than just a simple drag-and-drop series of actions. Knowing what Selenium is is a good thing.
Now, we will check out the practical example of handling Drag and drop in Selenium with Java. The following drag and drop example in Selenium is moving an element on a web page from one place to another.
import org. openqa. Selenium.By; import org. openqa. Selenium.WebDriver; import org. openqa. Selenium.WebElement; import org. openqa. Selenium. Chrome.ChromeDriver; import org. openqa. Selenium. Interactions.Actions; public class DragAndDropExample { public static void main(String[] args) { <br data-mce-bogus="1"> //Setting up WebDriver ``` WebDriver driver = new ChromeDriver(); driver.get("https://example.com/dragdrop"); // Find source and target elements WebElement sourceElement = driver.findElement(By.id("draggable")); WebElement targetElement = driver.findElement(By.id("droppable")); // Create an Action object Actions actions = new Actions(driver); //Drag and drop perform actions.dragAndDrop(sourceElement, targetElement).perform(); // Verify the drag-and-drop operation String droppedText = targetElement.getText(); if (droppedText.equals("Dropped!")) { System.out.println("Drag and drop successfully done!"); } else { System.out.println("Drag and drop not done successfully"); } // Close the browser driver.quit();
The dragAndDropBy() method achieves a more accurate and precise drag-and-drop operation. It moves an element by several pixels along the x and y axes. It is specifically helpful if one wants to drag an element not to the drop zone directly but to some area, which acts as a source for many other operations.
Following is how the dragAndDropBy() method works:
actions.dragAndDropBy(sourceElement, xOffset, yOffset).perform();
The parameters xOffset and yOffset indicate across which horizontal and vertical direction to move the element. Positive values move it to the right and downward, whereas negative values move it left and upward.
This method has the following uses:
Example with dragAndDropBy():
WebElement slider = driver.findElement(By.id("slider")); Actions actions = new Actions(driver); actions.dragAndDropBy(slider, 100, 0).perform();
The above code will slide some slider 100 pixels right.
There are some gotchas to take care of when dealing with dragAndDropBy():
The following is a bit more complex example of dragging an element onto the page to a specific coordinate:
WebElement draggable = driver.findElement(By.id("draggable")); Actions actions = new Actions(driver); // Get current position of element int startX = draggable.getLocation().getX(); int start = draggable.getLocation().getY(); // Calculate the farthest point to move (500, 300) int offset = 500 - starts; int offset = 300 - start; // Perform drag and drop actions.dragAndDropBy(draggable, xOffset, yOffset).perform();
This script will drag an element to coordinates (500, 300) of the page, regardless of its starting position.
During drag-and-drop operations, especially in automation testing, many exceptions and corner cases must be considered. For example, one may encounter the StaleElementReferenceException, where the page structure changes. One can overcome that by implementing retry logic or by using explicit waits on the elements so that they come into the state necessary for action execution.
Another critical factor is the cross-browser aspect. While Selenium tries to offer a consistent API across browsers, handling Drag and drop can be very different. Targeting cross-browser testing of your drag-and-dropDrag scripts is recommended to ensure consistent results.
You may have to combine a few actions to create more complex scenarios. For instance, this way, you could break down the Drag and drop operation over multiple statements to make the simulation more or less like the way a user would do it;
Actions actions = new Actions(driver); actions.clickAndHold(sourceElement) .moveToElement(targetElement) .release() .build() .perform();
The syntax of Drag and drop in Selenium Python differs, but the concepts remain almost the same. Here is how you would probably execute drag and drop in Python:
From selenium import webdriver
From Selenium. webdriver. Everyday.action_chains import ActionChains
driver = webdriver.Chrome() driver.get("https://example.com/dragdrop") source = driver.find_element_by_id("draggable") target = driver.find_element_by_id("droppable") actions = ActionChains
The way to drag and drop in Selenium sometimes depends on the peculiarities of the web application you’re testing. Some sites use custom JavaScript implementations on drag-and-drop functionality, but they do not respond to standard methods invoked by Selenium. In such cases, you can sometimes use scripting to simulate the Drag and Drag action directly:
String script = "function simulate(f,c,d,e){ "var b, a = null;" + "for (b in eventMatchers) {" + "a = eventMatchers[b];" + "if (a.test(c)) {" ) + " return f(a.run(c, d, e));" ) + "}" "}" + "};" + "var eventMatchers={" + "'HTMLEvents':/^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/", +" 'MouseEvents':/^(?:click|dblclick|mouse(?:down|up|over|move|out))$/}"; +" simulate(function(e,f,g){ "var d=e.ownerDocument||document;" + "var b=d.createEvent('MouseEvents');" + "b.initMouseEvent(f,true,true,d.defaultView,0,g.screenX,g.screenY,g.clientX,g.clientY,false,false,false,false,0,null); "e.dispatchEvent(b);" + "},arguments[0],arguments[1],arguments[2])"; ((JavascriptExecutor) driver).executeScript(script, sourceElement, "mousedown", 0); ((JavascriptExecutor) driver).executeScript(script, targetElement, "mousemove", 0); ((JavascriptExecutor) driver).executeScript(script, targetElement, "mouseup", 0);
As web applications become more complex, the need to master the drag-and-drop operation in Selenium increases. Knowing the subtleties of the implementation methods and adapting to different scenarios are ways to make automated scripts more robust and reliable. This information can help you prepare for selenium interview questions.
We have discussed many techniques, from basic drag-and-drop operations to advanced offset-based movements. These skills allow a tester to mimic complex user interaction with the application under test correctly. The more interactive web applications become, the more critical the skill will be in dragging and dropping operations. By knowing the multiple approaches and their applications, you can create more solid and versatile automation scripts.
In Selenium, drag-and-drop is a method for automating the drag-and-drop feature of web elements to another location, as end users do.
We can drag and drop a file using the sendKeys method available for the file input element. The sendKeys method will accept a full file path as an argument.
First, switch to the frame using a driver. switch ().frame(). Then, the drag-and-drop operation on elements within the frame is performed.
Use the Actions class in Selenium. Create an Actions object, then call dragAndDrop() or dragAndDropBy() methods to operate.
Course Name | Date | Details |
---|---|---|
Selenium Course | Class Starts on 23rd November,2024 23rd November SAT&SUN (Weekend Batch) | View Details |
Selenium Course | Class Starts on 25th November,2024 25th November MON-FRI (Weekday Batch) | View Details |
Selenium Course | Class Starts on 21st December,2024 21st December SAT&SUN (Weekend Batch) | View Details |
edureka.co