How to Enter value in textbox using Selenium Webdriver with Java?

As we have learnt in the previous posts how to identify the web elements. In this post we are going to automate an textbox by entering text using selenium webdriver.

First step to automate any webelement is to identify the Objects and store it in an variable.

Let’s use chropath to inspect textbox and identify the WebElement locator.

Observe that the textbox has id as “fname”. Let’s use this ID locator to identify the text box uniquely.
SendKeys() : Sendkeys is an predefined method from Selenium webdriver class, where we can type the input text into desired area of text box and text area fields.

Steps to Automate Text box field in Selenium WebDriver :

  1. Start writing code in an Java file.
  2. First let’s launch the browser (say using chrome here in this example).
  3. Enter the Appliction under test(AUT) url in the browser.

driver.get(“http://qacreators.com/FormToFill.html”);

  1. Maximize the browser window.

driver.manage().window().maximize();

  1. To identify the textbox WebElement we are using By.id(“fname”) (i.e id locator)

Let’s discuss about this line of code :

WebElement Fname = driver.findElement(By.id(“fname”));

–> driver : is the webdriver object.

–> findElement() : Used to identify or locate the elements to perform the operation.

–> By.id(“fname”) : By.id helps the findElement() to find the elements with ID locator. Here in this example we are using (id = fname) to identify the textbox field.

–> sendkeys() : Webdriver command used to enter the text into the specified textbox identified using locator.

–> WebElement Fname : Reference of the text box element is stored into Fname variable.

  1. To enter the text into the textbox use sendkeys method. Reference of WebElement i.e Fname with sendkeys method.

Fname.sendKeys(“sachin”);

  1. Execute the script by right click run as –> Java application.
  2. Once the script is executed we can observe the text is entered into the text box.
  3. Close the browser

Leave a Comment

Your email address will not be published. Required fields are marked *