selenium drag and drop not working is not a problem anymore because I'm going to explain three ways to drag and drop using selenium. I created a page to perform drag and drop actions and anyone can use it to automate their tasks. Click here to go to that page page
when we talk about drag and drop we can use Action class because consists of the built-in capability to handle keyboard and mouse events.
first, we need to create an object of Action class
Actions action = new Actions(-driver-);
using action class we can perform following user actions
click(): Clicks on web element.
doubleClick (): Double click on the web element.
contextClick() : Performs a right-click
clickAndHold(): Clicks at the given mouse location without releasing.
dragAndDrop(source, target): Clicks at the reference location and make movements to the place of the target without releasing the mouse.
dragAndDropBy(source, xOffset, yOffset): click-and-hold at the location, changes by a given offset value, then releases the mouse.
moveToElement(toElement): It moves to the mouse to the given element.
release(): Releases the pressed left mouse button at the existing mouse location.
actually, drag and drop command is predefined methods which will do our task
after that, we can use drag and drop command in drag and drop command is a convenience method that performs click-and-hold at the location of the source element, moves to the location of the target element, then releases the mouse.
action.dragAndDrop(webelementneedtodrag,webelementneedtodrop).perform();
perform() is used to execute the method of actions class
another method very similar to the above example it consists of MoveToElement and clickAndHold
to build and perform we can use always
WebElement frm = ChromeDriver.findElement(By.xpath(from));
WebElement o = ChromeDriver.findElement(By.xpath(to));
Actions action = new Actions(ChromeDriver);
action.moveToElement(frm)
.clickAndHold()
.moveToElement(o)
.build()
.perform();
below example object can move using the location-based locator
we can get web element location by getLocation() method and use of getX() and getY() using those methods e can locate element x-axis and y-axis of drop location.
WebElement From = ChromeDriver.findElement(By.xpath(from));
WebElement To = ChromeDriver.findElement(By.xpath(to));
int x = To.getLocation().getX();
int y = To.getLocation().getY();
Actions actions = new Actions(ChromeDriver);
actions.moveToElement(From)
.pause(Duration.ofSeconds(1))
.clickAndHold(From)
.pause(Duration.ofSeconds(1))
.moveByOffset(x, y)
.moveToElement(To)
.pause(Duration.ofSeconds(1))
.release().build().perform();
No comments:
Post a Comment