Monday, June 29, 2015

KEYBOARD OPERATIONS IN SELENIUM WEBDRIVER


The Keys class library allows us to reference the non alphabet/ text keys on the keyboard. This applies to keyboard keys like the ARROW keys, ALT, CTRL etc. Of course for text entries like "John", we can simply write: 



WebElementVariable.sendKeys("John");



The following codes will call the browser, load the google website and then simulate making an entry of "1999" into the search text box.



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; 

public class KeyboardOperations { 

         public static void main(String[] args) { 
                WebDriver driver = new FirefoxDriver(); 
                driver.navigate().to("http://www.google.co.uk"); // Actual loading of website 
               System.out.println("Make entries into Google Search using keyboard actions"); 
               WebElement searchInput = driver.findElement(By.className("gbqfif")); 
               String allKeys = ""+ Keys.NUMPAD1 + Keys.NUMPAD9 + Keys.NUMPAD9 + Keys.NUMPAD9; // 1 + 9 + 9 + 9 
               allKeys = allKeys + Keys.ENTER; // now add the ENTER key. We could also have done it above 
               searchInput.sendKeys(allKeys); // send the key presses into the text box 
        } 






Credits: http://www.logicandtricks.com/

No comments:

Post a Comment