January 17, 2017 17:08:25Hits: 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 class provides keyboard-related methods, SendKeys analog keyboard input, you can enter keys on the keyboard, you can also simulate the key combinations */
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 enter Test in the Baidu search box
Element.sendkeys (keys.back_space);//Delete last T
Element.sendkeys (keys.space);//SPACEBAR
Element.sendkeys ("ting");//Input 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{//use shortcut keys for right-click menus
Action.contextclick (Driver.findelement (by.id ("su")). Perform ();
Thread.Sleep (2000);
Action.sendkeys ("V"). Perform ();//analog keyboard input V
Action.sendkeys (Keys.arrow_down). Perform ()//press the DOWN Arrow 3 times through the keyboard
Action.sendkeys (Keys.arrow_down). Perform ();
Action.sendkeys (Keys.arrow_down). Perform ();
Action.sendkeys (Keys.enter). Perform ();//Press ENTER
}
public void Robotuse () throws exception{//use robot to simulate the operation of the mouse keyboard
Action.movetoelement (Driver.findelement (By.linktext ("login"));
try {
Thread.Sleep (2000);
Robot r=new Robot ();
R.mousepress (inputevent.button1_mask);//press the left mouse button
R.mouserelease (Inputevent.button1_mask);
R.keypress (Keyevent.vk_down);//Click the Down button of the keyboard once in the drop-down menu
R.keyrelease (Keyevent.vk_down);
R.keypress (keyevent.vk_enter);//Press ENTER
R.keyrelease (keyevent.vk_enter);//Release Enter
} catch (Awtexception e) {
E.printstacktrace ();
}
}
}
webdriver-keyboard operation for Java