webdriver-鍵盤操作 for java

來源:互聯網
上載者:User

標籤:boa   org   user   bar   stack   空格   public   http   robot   

 2017年01月17日 17:08:25閱讀數:2044import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;


public class selenium_keyboard_action {
/*Keys類提供了鍵盤的相關方法,sendKeys類比鍵盤輸入,可以輸入鍵盤上的按鍵,也可以類比按鍵組合*/
WebDriver driver=new FirefoxDriver();
Actions action=new Actions(driver);
public static void main(String[] args) throws Exception {
selenium_keyboard_action ska=new selenium_keyboard_action();
ska.init();
//ska.test1();
//ska.test2();
ska.robotUse();
}
public void init(){
driver.get("http://www.baidu.com/");
}
public void test1(){
WebElement element=driver.findElement(By.id("kw"));
element.sendKeys("test");//A向百度搜尋方塊中輸入test
element.sendKeys(Keys.BACK_SPACE);//刪除最後一個t
element.sendKeys(Keys.SPACE);//空格鍵
element.sendKeys("ting");//輸入ting
element.sendKeys(Keys.CONTROL,"a");//ctrl+a
element.sendKeys(Keys.CONTROL,"x");//ctrl+x
element.sendKeys(Keys.CONTROL,"v");//ctrlv
element.sendKeys(Keys.ENTER);//ctrl+a
}
public void test2() throws Exception{//對右鍵菜單使用快速鍵
action.contextClick(driver.findElement(By.id("su"))).perform();
Thread.sleep(2000);
//action.sendKeys("v").perform();//類比鍵盤輸入v
action.sendKeys(Keys.ARROW_DOWN).perform();//通過鍵盤按3次向下的箭頭
action.sendKeys(Keys.ARROW_DOWN).perform();
action.sendKeys(Keys.ARROW_DOWN).perform();
action.sendKeys(Keys.ENTER).perform();//按斷行符號鍵
}
public void robotUse() throws Exception{//使用robot類比滑鼠鍵盤的操作
action.moveToElement(driver.findElement(By.linkText("登入")));
try {
Thread.sleep(2000);
Robot r=new Robot();
//r.mousePress(InputEvent.BUTTON1_MASK);//按下滑鼠左鍵
//r.mouseRelease(InputEvent.BUTTON1_MASK);
r.keyPress(KeyEvent.VK_DOWN);//在下拉式功能表中點擊一次鍵盤的向下鍵
r.keyRelease(KeyEvent.VK_DOWN);

r.keyPress(KeyEvent.VK_ENTER);//按下斷行符號鍵
r.keyRelease(KeyEvent.VK_ENTER);//釋放斷行符號鍵
} catch (AWTException e) {
e.printStackTrace();
}
}
}

webdriver-鍵盤操作 for java

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.