Thursday, August 27, 2015

Dealing with input fields in Selenium WebDriver

I got few requests from people saying few of the input fields are not clearing the existing data though we do clear using clear() method in WebDriver and few of the inputs doesn't accept single quote('), double quote("), slash(\), double slash(\\) etc. 
Please have a look on below examples for resolving such issues.
Lets take an example input web element as below :
WebDriver driver = new FirefoxDriver();
WebElement element = driver.findElement(By.cssSelector("#addressInput"));
Clear Input Fields in Selenium WebDriver:
For clearing an input filed you can use either of the following ways:

Case: 1
element.clear();
Case: 2
element.click();
element.clear();
Case: 3
String oldValue = element.getAttribute("value");
if (oldValue.length() > 0) {
 element.clear();
}
Case: 4
element.click();
element.sendKeys(Keys.CONTROL + "a");
element.sendKeys(Keys.BACK_SPACE);
Case: 5
oldValue = element.getAttribute("value");
for (int i = 0; i < oldValue.length() * 2; i++) {
 element.click();
 element.sendKeys(Keys.DELETE);
 element.sendKeys(Keys.CONTROL + "a");
 element.sendKeys(Keys.BACK_SPACE);
 element.click();
 if (element.getAttribute("value").length() == 0) {
  break;
 }
}

Enter Text to Input Fields in Selenium WebDriver:
For entering various types of inputs to an input web element you can use the following approaches:

Case: 1 - Normal Text
element.sendKeys("Some Text");
Case: 2 - Single quote
element.sendKeys("'");// single quote
Sometimes if you try to enter single quote('), it may not enter if you keyboard setting in the system is changes. For example some smart systems enters 2 single quotes on pressing once or sometimes 2 single quotes shown only after pressing 2 times on the single quote key(i.e. on first time press it won't show a single quote). In such cases try using 2 single quotes as your input to input web elements
element.sendKeys("''");
Case: 3 - Double quote
element.sendKeys("\"");// double quote

// similar to above issue for single quote, same applies to double quotes
element.sendKeys("\"\"'"); 
Case: 4 - Single Slash
element.sendKeys("\\");// single slash(\)
Case: 5 - Double Slash
element.sendKeys("\\\\");// double slash(\\) 
Case: 6 - Special Characters
element.sendKeys("!@#$%^&*()_+}?");// special characters
Case: 7 - Scripts
element.sendKeys("<script>alert('Hello');</script>");// script

Hope this helps!