//通过Robot对象完成按键操作
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.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
public class RobotTest {
WebDriver driver;
String url="https://www.baidu.com";
@Test
public void TestDemo() throws InterruptedException {
driver.get(url);
WebDriverWait wait = new WebDriverWait(driver,10);
//显式等待
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("kw")));
driver.findElement(By.id("kw")).click();
setAndctrlVClipboardData("selenium");
pressTabKey();
pressEnterKey();
Thread.sleep(3000);
}
@BeforeMethod
public void beforeMethod() {
driver = new FirefoxDriver();
}
@AfterMethod
public void afterMethod() {
driver.quit();
}
public void setAndctrlVClipboardData(String string)
{
StringSelection stringSelection = new StringSelection(string);
//使用Toolkit对象的setContents将字符串放到剪切板中
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
Robot robot = null;
try{
robot = new Robot();
}catch(AWTException e1){
e1.printStackTrace();
}
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
}
public void pressTabKey()
{
Robot robot = null;
try{
robot = new Robot();
}catch(AWTException e1){
e1.printStackTrace();
}
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
}
public void pressEnterKey()
{
Robot robot = null;
try{
robot = new Robot();
}catch(AWTException e1){
e1.printStackTrace();
}
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
}
}
Toolkit类将各种组件与本机工具包绑定起来,Toolkit.getDefaultToolkit();是其最常用的方法,返回默认工具包,提供对本地最底层的java操作。
Toolkit.getDefaultToolkit().getSystemClipboard()获取系统剪切板
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("kw")));
driver.findElement(By.id("kw")).click();
一开始漏了这个点击事件,粘贴板粘贴selenium到地址栏……