Selenium getText

Lpgfmk picture Lpgfmk · May 22, 2014 · Viewed 57.2k times · Source

I want to getText() using By.id or By.cssSelector.

I managed to solve my problem by doing getAttribute("value"), but I don't understand why getText() doesn't work like I expect it, and I might need it so all help is appreciated.

Here is the Java code:

WebDriverWait wait = new WebDriverWait(driver, 10);
Boolean elementIsPresent = wait.until(ExpectedConditions.textToBePresentInElementValue(By.cssSelector("#general_service_name"),"[reg] general_service_name")); // true

//WebElement general_service_name = driver.findElement(By.cssSelector("#general_service_name"));
WebElement general_service_name = driver.findElement(By.id("general_service_name"));

// Display check
Boolean isDisplayed;
if(general_service_name.isDisplayed())  isDisplayed = new Boolean(true); else isDisplayed = false; //true

String text_empty = general_service_name.getText(); //""
String text_with_value = driver.findElement(By.id("general_service_name")).getAttribute("value"); //"[reg] general_service_name"

And HTML:

<input id="general_service_name" type="text" value="[reg] title" name="general_service_name" style="float:left;"/>

Answer

azraelAT picture azraelAT · May 22, 2014

http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/WebElement.html#getText()

getText() delivers the innerText of a WebElement.

Your input field does not have any inner Text. The text is found inside your value-attribute, hence accessing it via getAttribute("value") is the correct way to do it.