Selenium常用操作汇总二——如何把一个元素拖放到另一个元素里面(转)

Q群里有时候会有人问,selenium  webdriver怎么实现把一个元素拖放到另一个元素里面。这一节总一下元素的拖放。

下面这个页面是一个演示拖放元素的页面,你可以把左右页面中的条目拖放到右边的div框中。

http://koyoz.com/demo/html/drag-drop/drag-drop.html

现在来看看selenium webdriver是怎么实现drag and drop的吧。let‘s go!

import org.openqa.selenium.By;  
import org.openqa.selenium.WebDriver;  
import org.openqa.selenium.WebElement;  
import org.openqa.selenium.firefox.FirefoxDriver;  
import org.openqa.selenium.interactions.Actions;  
  
public class DragAndDrop {  
  
    /** 
     * @author gongjf 
     */  
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
        System.setProperty("webdriver.firefox.bin","D:\\Program Files\\Mozilla Firefox\\firefox.exe");    
        WebDriver dr = new FirefoxDriver();  
        dr.get("http://koyoz.com/demo/html/drag-drop/drag-drop.html");  
          
        //首先new出要拖入的页面元素对象和目标对象,然后进行拖入。  
        WebElement  element = dr.findElement(By.id("item1"));  
        WebElement  target = dr.findElement(By.id("drop"));  
        (new Actions(dr)).dragAndDrop(element, target).perform();  
          
        //利用循环把其它item也拖入  
        String id="item" ;  
        for(int i=2;i<=6;i++){  
            String item = id+i;  
            (new Actions(dr)).dragAndDrop(dr.findElement(By.id(item)), target).perform();  
        }  
    }  
  
}  

 代码很简单,需要注意的是(new Actions(dr)).dragAndDrop(element, target).perform();这句话中,dragAndDrop(element, target)这个方法是定义了“点击element元素对象,然后保持住,直到拖到目标元素对象里面才松开”这一系列动作的Actions,如果你不调用perform()方法,这个Actions是不会执行的。over!

猜你喜欢

转载自www.cnblogs.com/xinxin1994/p/9207183.html