Как выполнить перетаскивание с использованием selenium-webdriver, когда целевой и целевой элементы находятся в разных кадрах?
Мне нужно перетащить изображение и перенести его в компонент CQ5. Изображение и компонент находятся в разных кадрах.
Вот код, который не работал, поскольку webelement destination
не удалось найти, когда целевой кадр был активным.
new Actions(driver).dragAndDrop(target, destination).perform();
Я также попытался переключить кадр между действиями как:
Actions builder = new Actions(driver);
Actions action = builder.clickAndHold(target);
driver.switchTo().frame("newFrame"); //switching frames
builder.moveToElement(destination);
builder.release(destination);
builder.build();
action.perform();
Это тоже не сработало. Затем я попытался перемещать изображение с помощью смещения
new Actions(driver).dragAndDropBy(target, x, y).perform(); // x and y
Это переместило изображение, но компонент его не захватил, возможно, потому что действие было слишком быстрым. Есть ли способ сделать такое падение перетаскивания?
Спасибо заранее.
Ответы
Ответ 1
Вам нужно разбить его на две части.
// grab your element
Actions builder = new Actions(driver);
Actions action = builder.clickAndHold(target);
builder.build();
action.perform();
// switch to the frame (you havent told webdriver to un-grab
driver.switchTo().frame("newFrame"); //switching frames
// move and drop
Actions builder = new Actions(driver);
Actions action = builder.moveToElement(destination);
builder.release(destination);
builder.build();
action.perform();
Ответ 2
Кажется, есть некоторые проблемы с перетаскиванием selenium/webdriver. Я представил дефект с людьми селена, http://code.google.com/p/selenium/issues/detail?id=4420
Надеюсь, мы получим положительный ответ.
Ответ 3
Кто-нибудь нашел решение для Adobe CQ 5.5?
Я столкнулся с той же проблемой с adobe CQ 5.5, я пытался несколько разных способов, я могу получить изображение, чтобы удалить зону, но как только оно там, изображение все еще кажется неактивным, и падение его не имеет смысла. Я понял, что это потому, что указатель мыши не движется с изображением, поэтому падение не имеет смысла. Я добавил код, чтобы переместить мышь в зону выпадения, но выглядит так, как будто команды работают отдельно, поэтому все еще не могут отказаться, пожалуйста, любое предложение.
Вот мой код (не работает на CQ 5.5)
String handle = driver.getWindowHandle(); // for main window
//Переключиться в окно, чтобы можно было выбрать изображение
driver.switchTo().window(handle);
WebElement dragble = driver.findElement(By.xpath("//xpath"));
Actions builder = new Actions(driver);
builder.clickAndHold(dragble);
Action action2 = builder.build();
action2.perform();
//Затем переключитесь на iframe
driver.switchTo().frame("cq-cf-frame");
WebElement droppable = driver.findElement(By.cssSelector("#cssSelector of droppable"));
//Робот для указания мыши на недоступную зону
Point coordinates = driver.findElement(By.cssSelector("#cssSelector of droppable")).getLocation();
Robot robot = new Robot();
//Найти местоположение для элемента droppable
int x = driver.findElement(By.cssSelector("#ext-comp-1271")).getLocation().getX();
int y = driver.findElement(By.cssSelector("#ext-comp-1271")).getLocation().getY();
//Перемещение dragble to droppable
builder = new Actions(driver);
builder.moveByOffset(x,y).perform().
builder.build();
builder.release();
robot.mouseMove(coordinates.getX(),coordinates.getY()+120);
builder.release(droppable).perform();
Ответ 4
String source = "xpath_of_source";
String destination = "xpath_of_destination";
// grab your element
Actions builder = new Actions(driver);
Actions action = builder.clickAndHold(driver.findElement(By.xpath(source)));
builder.build();
action.perform();
// switch to the frame
driver.switchTo().frame("newFrame"); //switching frames
// move and drop
builder = new Actions(driver);
action = builder.moveToElement(driver.findElement(By.xpath(destination)));
builder.release(driver.findElement(By.xpath(destination)));
builder.build();
action.perform();
Ответ 5
Selenium webdriver обеспечивает функцию перетаскивания. Попробуйте это
WebElement element = driver.findElement(By.name("source"));
WebElement target = driver.findElement(By.name("target"));
(new Actions(driver)).dragAndDrop(element, target).perform();
Ответ 6
Этот код работает на CQ 5.5
driver.switchTo().defaultContent();
Actions builder = new Actions(driver);
builder.clickAndHold(target);
Action action = builder.build();
action.perform();
driver.switchTo().frame("cq-cf-frame");
builder.moveToElement(destination);
builder.release(destination);
action = builder.build();
action.perform();
Ответ 7
Вышеуказанные решения не работали для меня в CQ 5.5 и CQ 5.6
Это работает:
Actions builder = new Actions(driver);
builder.clickAndHold(sideKickComponent);
Action action = builder.build();
action.perform();
driver.switchTo().frame("cq-cf-frame");
builder = new Actions(driver);
builder.moveToElement(destination).perform();
builder.build();
builder.release();
builder.release(destination).perform();
Этот метод позволяет удобно размещать компоненты:
public void addComponentByDragAndDrop(String sideKickComponentName, WebElement destination){
driver.switchTo().defaultContent();
WebElement sidekick = driver.findElement(By.id("cq-sk"));
List<WebElement> components =sidekick.findElements(By.tagName("button"));
WebElement sideKickComponent = null;
for (WebElement webElement : components) {
if (webElement.getText().equals(sideKickComponentName)) {
sideKickComponent = webElement;
break;
}
}
if (sideKickComponent == null) {
fail("SideKick component with the name: "+sideKickComponentName + " was not found.");
}
Actions builder = new Actions(driver);
builder.clickAndHold(sideKickComponent);
Action action = builder.build();
action.perform();
driver.switchTo().frame(Consts.CQ_MAIN_FRAME);
builder = new Actions(driver);
builder.moveToElement(destination).perform();
builder.build();
builder.release();
builder.release(destination).perform();
}
Ответ 8
Приведенный ниже код работает, надеюсь, что это поможет:
WebElement dragElement = (WebElement) elements.get(sourceElement);
Actions builder = new Actions(driver);
Actions action = builder.clickAndHold(dragElement);
action.build().perform();
driver.switchTo().frame("cq-cf-frame");
WebElement dropElement = driver.findElement(By.id("ext-comp-1411"));
builder.moveToElement(dropElement).build().perform();
//click the destination
builder.click(dropElement).build().perform();
//back to main page to release the hold mouse
driver.switchTo().defaultContent();
builder.release(dragElement).build().perform();
Ответ 9
Чтобы выполнить перетаскивание из iframe в другой, вам нужно указать все свои действия в iframe исходного веб-элемента. Для этого вы должны получить родительский объект iframe и использовать его, т.е. CqFrameParent, который является div, который имеет целевой iframe.
Поскольку источник и цель принадлежат одному iframe, не нужно делать переключение iframe для этого.
builder.moveElement(CqFrameParent(), targetX, targetY).build().perform();
builder.release().build().perform();
Ответ 10
У меня был тот же самый prb, что и вы. Я не могу дрочить и отбрасывать два элемента из одного кадра в пыльник.
верхушки ансеров верны, но из селена 3 это решение больше не работает.
Занято преобразовать исходный элемент (после щелчка мышью) в позицию 0,0, а затем переместить его под второй кадр. например 150 150.
Actions builder = new Actions(driver);
// switsh to the source frame
driver.switchTo().frame("sourceFrame");
// take the element with mouse
builder.clickAndHold(sourceElt).build().perfom();
// move mouse to the top of the source frame
builder.moveToElement(sourceElt, 0, 0 ).build().perfom();
// move the mouse under the target frame (specific to your case)
builder.moveToElement(sourceElt, 150,200).build().perfom();
// switsh to the target frame
driver.switchTo().frame("targetFrame");
builder.moveToElement(targetElt).build().perform();
builder.release(target).build().perform();
Надеюсь, я тоже тебе помогу.
Ответ 11
Создать объект класса действий
Actions act=new Actions(driver);
Найти элемент xpath, который нужно перетащить
WebElement drag=driver.findElement(By.xpath("put x path"));
Найти элемент xpath, где нам нужно отбросить
WebElement drop=driver.findElement(By.xpath("put x path"));
Перетащите элемент в пункт назначения
act.dragAndDrop(drag, drop).build().perform();
Чтобы использовать перетаскивание в CQ, сначала используйте функцию двойного щелчка и поместите любой компонент, затем попробуйте описанный выше метод.