Robot 模擬操作鍵盤 實現復制粘貼功能;


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); } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM