How to gettext() of an element in Selenium Webdriver
Asked Answered
D

4

12

I am finding a textbox by its ID. I need to get the content which is already there inside the text box. For that I am using the gettext() method, but it is returning the ID value.

The content in the text box is: Santhosh

The output I am getting is = [[FirefoxDriver: firefox on XP (c0079327-7063-4908-b20a-a606b95830cb)] -> id: ctl00_ContentPlaceHolder1_txtName]

The code is below

Code

WebElement TxtBoxContent = driver.findElement(By.id(WebelementID));
TxtBoxContent.getText();
System.out.println("Printing " + TxtBoxContent);

Result

Printing [[FirefoxDriver: firefox on XP (c0079327-7063-4908-b20a-a606b95830cb)] -> id: ctl00_ContentPlaceHolder1_txtName]
Discalced answered 28/2, 2014 at 6:35 Comment(2)
If you add the HTML, we can better help you find the element, and the text.Homeroom
Another question asks why (to the solution), but there isn't a proper answer (yet): Why is getText() in Selenium not working for <textarea> elements, but getAttribute(“value”) is?Garmon
H
14

You need to print the result of the getText(). You're currently printing the object TxtBoxContent.

getText() will only get the inner text of an element. To get the value, you need to use getAttribute().

WebElement TxtBoxContent = driver.findElement(By.id(WebelementID));
System.out.println("Printing " + TxtBoxContent.getAttribute("value"));
Homeroom answered 28/2, 2014 at 6:44 Comment(5)
i tried your code But it is not returning any text at all it is just showing : Printing : there is no text after that please help - the text content is in text box i need to fetch the textDiscalced
<input id="ctl00_ContentPlaceHolder1_txtName" class="textboxnew" type="text" style="width:100%;" onblur="findduplicate(this.value);" maxlength="100" value="Santhosh" name="ctl00$ContentPlaceHolder1$txtName"Discalced
i need to fetch the value i.e., Santhosh in itDiscalced
Thanks A LOT now its working. Thanks for Saving my Day.... i am new to selenium so bit problem in analyzing the codesDiscalced
For Python it would be ...TxtBoxContent.get_attribute("value").Garmon
M
4
text = driver.findElement(By.id('p_id')).getAttribute("innerHTML");
Mammiemammiferous answered 15/1, 2016 at 0:47 Comment(2)
and some explanationPyrrolidine
I could not get the test from the element with the other solutions. This worked for meScatter
W
4

You need to store it in a String variable first before displaying it like so:

String Txt = TxtBoxContent.getText();
System.out.println(Txt);
Wiese answered 22/7, 2016 at 12:58 Comment(0)
T
0

Python

element.text

Java

element.getText()

C#

element.Text

Ruby

element.text
Towers answered 27/3, 2023 at 8:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.