Many automation QAs confuse with which selenium method we need to use to fetch the textbox value from the web application.
- getText()
- getAttribute(“value”)
The short answer is getAttribute("value")
Let’s consider qavbox.github.io/demo/signup
The username text box with id=username
String unamevalue; unamevalue = driver.findElement(By.id("username")).getAttribute("value") System.out.println(unamevalue);
Output – qavbox
getAttribute(“value”) is used to fetch the value present in side element’s value attribute if any, also used to fetch the text entered to a textBox/text area.
You will not get any output when you use getText()
driver.findElement(By.id("username")).getText()
getText() always returns the text that is present on the DOM in between the open and close of tagName
e.g – <input>someText</input>
For example –
In the above image, “Full Name” text is present inside <label …> </label> and getText() returns the string as “Full Name”
String fNameText= ""; fNameText = driver.findElement(By.id("username")).getText() System.out.println(fNameText);
Output – Full Name
Hope this helps!