使用Selenium WebDriver和Java,拖放在iFrame中不起作用

时间:2017-09-18 04:48:41

标签: java selenium iframe webdriver action

我正在尝试使用Selenium和Java执行拖放操作并且它无法正常工作..原因可能是什么..它没有给我任何错误但它只是没有发生..

这是我的代码。

public class ActionDragDrop {

    public static void main(String[] args) throws InterruptedException {

        WebDriver driver = new ChromeDriver();
        driver.get("https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop");
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        WebElement f=driver.findElement(By.xpath("//*[@id='iframeResult']"));
        driver.switchTo().frame(f);

        WebElement drag = driver.findElement(By.xpath("//*[@id='drag1']"));
        WebElement drop = driver.findElement(By.xpath("//*[@id='div1']"));

        Actions builder = new Actions(driver);
        Actions dragAndDrop = builder.clickAndHold(drag);
        builder.moveToElement(drop);
        builder.release(drop);
        builder.build();
        dragAndDrop.perform();  
    } 
}

3 个答案:

答案 0 :(得分:0)

您将首先切换到iframe以执行拖放操作:

driver.switchTo().frame(0);                      //Move inside to the frame. 
WebElement body = driver.findElement(By.tagName("body"));
body.click();
WebElement from = driver.findElement(By.xpath("//your xpath")); 
Actions act = new Actions(driver);
act.clickAndHold(from).build().perform();
Thread.sleep(4000);
driver.switchTo().defaultContent();              //Move outside to the frame.

driver.switchTo().frame(1);                     //Move inside to another frame.
WebElement body = driver.findElement(By.tagName("body"));
body.click();
WebElement to = driver.findElement(By.id("guide_RIGHT_SAFETY_rect"));
act.clickAndHold(to).moveToElement(to).release(to).build().perform();
Thread.sleep(2000);
driver.switchTo().defaultContent();                //Move outside to another frame.

注意:请使用您的xpath,id,classname等,我刚刚复制了一个示例。或多或少的想法应该是相同的。

答案 1 :(得分:0)

请尝试以下代码。

由于您的fromto webelement位于同一iframe内。首先,您需要切换iframe.

driver.get("https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop");
driver.manage().window().maximize();

driver.switchTo().frame("iframeResult");   //Move inside to the frame. 
WebElement body = driver.findElement(By.tagName("body"));
body.click();
WebElement from = driver.findElement(By.xpath("//img[@id='drag1']")); 
WebElement to = driver.findElement(By.xpath("//div[@id='div1']"));

Actions act = new Actions(driver);
act.clickAndHold(from).perform();
Thread.sleep(4000);
act.clickAndHold().moveToElement(to).release(to).build().perform();
Thread.sleep(2000);
driver.switchTo().defaultContent();    //Move outside to the frame.

答案 2 :(得分:0)

我做了很多实验,终于在Python中找到了下面的代码。

DragAndDrop的失败不是由iframe引起的。

只需分开每个步骤并执行即可。

# drag leftbox and drop on rightbox

actions = ActionChains(driver)
actions.click_and_hold(leftbox).perform()
sleep(4)
actions.move_to_element(rightbox).perform()
sleep(4)
actions.release(rightbox).perform()