This post was most recently updated on June 14th, 2019
Code to perform key press events , mouse left right operations using action class.
Functions for keyboard | Uses |
---|---|
keyDown(java.lang.CharSequence key) | To simulate key down event on current location. |
keyDown(WebElement target, java.lang.CharSequence key) | To simulate key down event on target element. |
keyUp(java.lang.CharSequence key) | To simulate key up event on current location. |
keyUp(WebElement target, java.lang.CharSequence key) | To simulate key up event on target element. |
sendKeys(WebElement target, java.lang.CharSequence… keys) | To simulate send keys on targeted element. |
sendKeys(java.lang.CharSequence… keys) | To simulate send keys on current location. |
Code snippet: For key press simulation using different functions available in Action class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.interactions.Action; import org.openqa.selenium.interactions.Actions; public class SeleniumMain { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "D:/chromedriver.exe"); WebDriver driver; ChromeOptions cOptions=new ChromeOptions(); cOptions.addArguments("--start-maximized"); driver=new ChromeDriver(cOptions); driver.get("https://www.youidraw.com/apps/painter/"); //create object of Actions class Actions builder=new Actions(driver); WebElement text=driver.findElement(By.id("text")); WebElement canvas=driver.findElement(By.id("catch")); // Performed left click using Keys on web element Action leftClickOnTextIcon=builder.sendKeys(text, Keys.LEFT).build(); leftClickOnTextIcon.perform(); //Method1: // Performed left click using Keys on web element Action leftClickOnCanvas =builder.sendKeys(canvas, Keys.LEFT).build(); leftClickOnCanvas.perform(); //Use of keyDown and keyUp Action enterDataOnTextCanvas=builder.keyDown(Keys.SHIFT).sendKeys("user").keyUp(Keys.SHIFT).build(); enterDataOnTextCanvas.perform(); //Method2:Comment Method1 Action enterDataOnTextCanvas2= builder.keyDown(Keys.SHIFT).sendKeys(canvas,"user").keyUp(Keys.SHIFT).build(); enterDataOnTextCanvas2.perform(); //commented to see result //driver.quit(); } } |