实例目的:通过Robot对象操作键盘上的按键完成复制、粘贴、切换焦点和回车等常用操作。
实例代码:
package cn.om.webdriverapi; import org.testng.annotations.Test; import org.testng.annotations.BeforeMethod; import java.awt.AWTException; import java.awt.Robot; import java.awt.Toolkit; import java.awt.datatransfer.StringSelection; import java.awt.event.KeyEvent; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.AfterMethod; //Robot对象操作键盘 public class TestRobotOperateKeboard { WebDriver driver; String url; @Test public void testRobotOperateKeboard() { driver.get(url); // 使用显式等待,判断页面是否显示搜索框 WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(ExpectedConditions.presenceOfElementLocated(By.id("kw"))); // 调用封装好的函数setAndctrlVClipboardData,将“selenium”关键字使用ctrl+v组合件方式粘贴到搜索框中 setAndctrlVClipboardData("selenium"); // 调用封装好的pressTabKey函数,按tab键,将焦点从搜索框转移到搜索按钮上。 pressTabKey(); // 调用封装好的函数pressEnterKey,按Enter键会触发搜索结果的提交 pressEnterKey(); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* * 封装粘贴函数,将函数的入参放入剪贴板中,然后在使用Robot 对象的keyPress和keyRelease函数来模拟Ctrl+V组合键完成粘贴操作 */ public void setAndctrlVClipboardData(String s) { // 声明StringSelection对象,并使用函数的string参数来完成实例化 StringSelection stringSelection = new StringSelection(s); // 使用Toolkit对象的setContents方法将字符串放到剪切板上 Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null); // 声明Robot对象 Robot robot = null; try { robot = new Robot(); } catch (AWTException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 调用KeyPress来实现按下Crtl键 robot.keyPress(KeyEvent.VK_CONTROL); // 调用KeyPress来实现按下V键 robot.keyPress(KeyEvent.VK_V); // 调用KeyPress来释放V键 robot.keyRelease(KeyEvent.VK_V); // 调用KeyPress来释放crtl键 robot.keyRelease(KeyEvent.VK_CONTROL); } public void pressTabKey() { Robot robot=null; try { robot=new Robot(); } catch (AWTException e) { // TODO Auto-generated catch block e.printStackTrace(); } robot.keyPress(KeyEvent.VK_TAB); robot.keyRelease(KeyEvent.VK_TAB); } public void pressEnterKey() { Robot robot=null; try { robot=new Robot(); } catch (AWTException e) { // TODO Auto-generated catch block e.printStackTrace(); } robot.keyPress(KeyEvent.VK_ENTER); robot.keyRelease(KeyEvent.VK_ENTER); } @BeforeMethod public void beforeMethod() { url = "http://www.baidu.com"; System.setProperty("webdriver.firefox.bin", "D:/Mozilla Firefox/firefox.exe"); driver = new FirefoxDriver(); } @AfterMethod public void afterMethod() { driver.quit(); } }