Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to gettext() of an element in Selenium Webdriver

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]
like image 468
Santhosh S Avatar asked Feb 28 '14 06:02

Santhosh S


People also ask

How do you getText from an element in Selenium?

getText() Method in Selenium This method helps retrieve the text, which is basically the innertext of a WebElement. getText() method returns string as a result. It removes the whitespaces if present in the front and back of the string.

Is getText () a WebElement method?

What Is getText() Method? The Selenium WebDriver interface has predefined the getText() method, which helps retrieve the text for a specific web element. This method gets the visible, inner text (which is not hidden by CSS) of the web-element.

In which interface getText () and getAttribute () is available?

getText() is a method which gets us the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing white space. The getAttribute() method is declared in the WebElement interface, and it returns the value of the web element's attribute as a string.

What is the return type of getText () and getAttribute ()?

The getText() method simply returns the visible text present between the start and end tags (which is not hidden by CSS). The getAttribute() method on the other hand identifies and fetches the key-value pairs of attributes within the HTML tags.


2 Answers

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"));
like image 87
Richard Avatar answered Sep 19 '22 06:09

Richard


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

String Txt = TxtBoxContent.getText();
System.out.println(Txt);
like image 41
Sags Avatar answered Sep 22 '22 06:09

Sags