Search code examples
seleniumdrag-and-drop

Drag and drop in Selenium


In https://www.globalsqa.com/demo-site/draganddrop/ I need to drag and drop picture with the text "High Tatras" into Trash section.

@Test
void task1() {
    System.setProperty("webdriver.chrome.driver", "C:\\Users\\DELL\\Desktop\\New folder\\chromedriver.exe");
    WebDriver webDriver = new ChromeDriver();
    try {
        webDriver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
        webDriver.get("https://www.globalsqa.com/demo-site/draganddrop/");

        WebElement from = webDriver.findElement(By.xpath("//*[@id=\"gallery\"]/li[1]"));

        WebElement to = webDriver.findElement(By.xpath("//*[@id=\"trash\"]"));

        Actions actions = new Actions(webDriver);
        actions.dragAndDrop(from, to).build().perform();
    } finally {
        webDriver.close();
    }
}

Solution

  • Both the from and to elements are inside the iframe.
    So, to access these elements you need to switch into that iframe first. Your code will look as following:

    @Test
    void task1() {
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\DELL\\Desktop\\New folder\\chromedriver.exe");
        WebDriver webDriver = new ChromeDriver();
        try {
            webDriver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
            webDriver.get("https://www.globalsqa.com/demo-site/draganddrop/");
            
            driver.switchTo().frame(driver.findElement(By.xpath("//div[@rel-title='Photo Manager']//iframe")));
    
            WebElement from = webDriver.findElement(By.xpath("//*[@id='gallery']/li[1]"));
    
            WebElement to = webDriver.findElement(By.xpath("//*[@id='trash']"));
    
            Actions actions = new Actions(webDriver);
            actions.dragAndDrop(from, to).build().perform();
        } finally {
            webDriver.close();
        }
    }