1.代码逻辑 :
a.封装一个粘贴的方法体:setAndctrlVClipboardData(String string);参数string是需要粘贴的内容 ;
b.声明一个StringSelection stringSelection 对象来接受粘贴的内容;
c.使用Toolkit 对象的setContents放需要粘贴的内容放入到粘贴板中;Toolkit.getDefaultToolkit().getSystemClipboad().setContents(contents, owner);
d.在该方法中使用Robot来模拟键盘crtl+v的操作;
package testNGPractice; 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.ie.InternetExplorerDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import scr.comm.OpenBrowserInfo; public class RobotTestDemo { public WebDriver driver ; @Test public void Test() { String url="http://www.sogou.com/"; driver.navigate().to(url); WebDriverWait wait= new WebDriverWait(driver,10); wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("query"))); setAndctrlVClipboardData("我的人生我做主!"); pressTabKey(); pressEnterKey(); try{ Thread.sleep(3000); }catch(InterruptedException e){ e.getStackTrace(); } } @BeforeMethod public void beforeMethod() { OpenBrowserInfo.IeDriver(); driver = new InternetExplorerDriver(); } @AfterMethod public void afterMethod() { driver.quit(); } public void setAndctrlVClipboardData(String string){ //声明一个StingSelection 对象,并使用String的参数完成实例化; StringSelection stringSelection = new StringSelection(string); //使用Toolkit对象的setContents将字符串放到粘贴板中 ; Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null); Robot robot = null ; try{ robot = new Robot(); }catch(AWTException e){ System.out.println(e.getStackTrace()); }
//按下crtl v键 ; robot.keyPress(KeyEvent.VK_CONTROL); robot.keyPress(KeyEvent.VK_V);
//释放crtl v 键 robot.keyRelease(KeyEvent.VK_V); robot.keyRelease(KeyEvent.VK_CONTROL); } public void pressTabKey(){ Robot robot=null ; try{ robot = new Robot(); }catch(AWTException e){ e.getStackTrace(); } robot.keyPress(KeyEvent.VK_TAB); robot.keyRelease(KeyEvent.VK_TAB); } public void pressEnterKey(){ Robot robot= null ; try{ robot = new Robot(); }catch(AWTException e){ e.getStackTrace(); } robot.keyPress(KeyEvent.VK_ENTER); robot.keyRelease(KeyEvent.VK_ENTER); } }