Tuesday, 9 August 2016

Selenium2: WebDriver: sendKeys: Write text to textbox, textarea

WebElement interface provide sendKeys method which writes some text to textbox (or) textarea. Following is the signature of sendKeys method.

void sendKeys(CharSequence... keysToSend);

I am going to populate username, password fields using WebDriver instance and submit the form. Following is the login.jsp page, I am going to submit.


login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 <h1>Login Page</h1>

 <form method="post" action="loginCheck">
  <table>
   <tr>
    <td>UserName :</td>
    <td><input type="text" name="userName" /></td>
   </tr>
   <tr>
    <td>Password</td>
    <td><input type="password" name="password" /></td>
   </tr>
   <tr>
    <td><input type="reset" value="Clear" /></td>
    <td><input type="submit" value="submit" /></td>
   </tr>
  </table>

 </form>
</body>
</html>

How to populate username field?
Observe the login.jsp file. ‘input’ element has a name ‘userName’ associated with it.

<input type="text" name="userName" />

You can populate the username textbox, by accessing the element by name. Following Java snippet is used to populate username field. ‘driver.findElement(…) method is used to locate a UI element. By class is used to locate elements within a document

WebElement userNameElement = driver.findElement(By.name("userName"));
userNameElement.sendKeys("HariKrishna");

Same in the case of password field also. Following snippet is used to populate password field.

WebElement passwordElement = driver.findElement(By.name("password"));
passwordElement.sendKeys("password123");

After populating the fields, you can submit the form by using any WebElement instance.

userNameElement.submit();
         (OR)
passwordElement.submit();


Following is the complete working application.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class App {
 public static void main(String[] args) {
  WebDriver driver = new FirefoxDriver();
  driver.get("http://localhost:8080/application/getLoginPage");

  WebElement userNameElement = driver.findElement(By.name("userName"));
  WebElement passwordElement = driver.findElement(By.name("password"));

  userNameElement.sendKeys("HariKrishna");
  passwordElement.sendKeys("password123");

  passwordElement.submit();
 }
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment