Actions類
一、鼠標右擊、雙擊
Java代碼
//定位百度首頁右上角 新聞 WebElement Xw=driver.findElement(By.xpath("//*[@id='u1']/a[1]")); //new Actions對象 Actions RightClick=new Actions(driver); //在 新聞 上點擊鼠標右鍵 RightClick.contextClick(Xw).perform(); Thread.sleep(3000); //雙擊 新聞 RightClick.doubleClick(Xw).perform(); Thread.sleep(3000);
二、鼠標移動到指定位置
java代碼
//定位百度首頁右側 更多產品 WebElement gdcp=driver.findElement(By.xpath("//*[text()='更多產品']")); //實例化Actions Actions MTE=new Actions(driver); //鼠標移動到 更多產品上 MTE.moveToElement(gdcp).perform(); //等待3秒 Thread.sleep(3000);
三、拖動元素
java代碼
//定位要拖動的元素 WebElement dg=driver.findElement(By.xpath("//*[text()='拖動']")); //實例化Actions Actions tuodong=new Actions(driver); Thread.sleep(1000); //將定位的dg拖動(100,300) tuodong.dragAndDropBy(dg,100,300).perform(); Thread.sleep(2000);
四、將元素拖到另一元素上
java代碼
//定位要拖動的元素 WebElement ElementStart=driver.findElement(By.xpath("//*[text()='拖動']")); //定位終點上的元素 WebElement ElementEnd=driver.findElement(By.xpath("//*[text()='tuodongduodong']")); //實例化Actions Actions CM=new Actions(driver); CM.clickAndHold(ElementStart) .moveToElement(ElementEnd) .release(ElementEnd) .perform();
五、下拉框多選
HTML源碼
<td>多選下拉框</td> <select id="selects" multiple="multiple"> <option label="java">java</option> <option label="c">c</option> <option label="c++">c++</option> <option label="VB">VB</option> <option label="php">php</option> <option label="python">python</option> <option label="ruby">ruby</option> </select>
Java代碼
//獲取下拉框中所有的文本元素 List<WebElement> list=driver.findElements(By.xpath("//*[@id='selects']/option")); //實例化Actions Actions AtList=new Actions(driver); //按下CONTROL鍵 AtList.keyDown(Keys.CONTROL) //點擊第一個元素,第一個元素是被默認選中的,所以不想選擇第一個就再點一下 .click(list.get(0)) //點擊第二個元素 .click(list.get(2)) //點擊第四個元素 .click(list.get(3)) //釋放CONTROL鍵 .keyUp(Keys.CONTROL) //執行 .perform();
Robot類
按下按鍵 keyPress()
釋放按鍵 keyRelease()
public void Robot() throws AWTException{
driver.get("https://www.baidu.com/");
//實例化Robot
Robot rb=new Robot();
//按下CONTROL鍵
rb.keyPress(KeyEvent.VK_CONTROL);
//按下s鍵
rb.keyPress(KeyEvent.VK_S);
Thread.sleep(1000);
//松開s鍵
rb.keyRelease(KeyEvent.VK_S);
//松開CONTROL鍵
rb.keyRelease(KeyEvent.VK_CONTROL);
}