How to get typed text from a textbox by using Selenium Webdriver?


We can get the typed text from a textbox with Selenium webdriver. Firstly, we have to enter text in the text box (after being identified with any locators) with the help of the sendKeys method.

Then apply the method getAttribute to obtain the text entered in that field and pass the parameter value to that method. Let us make an attempt to obtain the value entered in the Google search box −

Syntax

WebElement m = driver.findElement(By.name("q"));
String st = m.getAttribute("value");

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class GetTextTyped{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
"C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.google.com/");
      // identify element
      WebElement t =driver.findElement(By.name("q"));
      t.sendKeys("Tutorialspoint");
      // obtain value with getAttribute
      System.out.println("Value is: " + t.getAttribute("value"));
      driver.quit();
   }
}

Output

Updated on: 03-Apr-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements