How do you enter text in the edit box in Selenium?


We can enter text in the edit box in Selenium by the following ways −

  • By invoking sendkeys() method.

  • Using the class JavascriptExecutor.

Code Implementation with sendkeys() method.

Example

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 java.util.concurrent.TimeUnit;
public class TextEnter {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",       "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      driver.findElement(By.className("gsc-input"))
      .sendKeys("Selenium");
      driver.close();
   }
}

Code Implementation with class JavascriptExecutor method.

Example

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 java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class EnterScripting {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",       "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm"
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // Create Javascript object
      JavascriptExecutor js = (JavascriptExecutor)driver;
      // Issue command to enter the text
      js.executeScript("document.getElementById('gsc-i-id1').value = 'Selenium';");
      driver.close();
   }
}

Updated on: 10-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements