Matthew
Matthew

Reputation: 395

Selenium WebDriver get text from input field

I'm writing a test to assert the default text value within an <input> tag. However, it's not playing ball:

Assert.assertThat(webDriver.findElement(By.id("inputTag")).getText(), Matchers.is("2"));

Upvotes: 17

Views: 50518

Answers (3)

Ory Zaidenvorm
Ory Zaidenvorm

Reputation: 1054

From latest Selenium, GetAttribute method is marked as obsolete (will be removed from Selenium 6) so instead need to do (C#)-

webDriver.FindElement(By.Id("inputTag")).GetDomProperty("value")

This method will get an element's attribute that is NOT in the DOM (if the attribute is in the DOM then user can call GetDomAttribute(string attributeName))

Upvotes: 0

Philipp
Philipp

Reputation: 11391

The most reliable solution I found, is executing a JavaScript script and return the value attribute of the HTMLInputElement from JavaScript.

I have tested this in several ways and the value was always correct, even after changing the input field value.

PHP

$input = $driver->findElement( WebDriverBy::id( 'inputTag' ) );
$value = $driver->executeScript( 'return arguments[0].value', $input );
// A custom PHP function that returns the value of an input field:
function getValue(RemoteWebDriver $driver, WebDriverBy $by ) {
    return $driver->executeScript( 
        'return arguments[0].value', 
        $driver->findElement( $by ) 
    );
}

// Sample usage:
$value = getValue( $driver, WebDriverBy::id( 'inputTag' ) );

Java

//driver being your WebDriver
JavascriptExecutor js = (JavascriptExecutor) driver;  

WebElement inpElement = driver.findElement(By.id("inputTag"));
String text = (String) js.executeScript("return arguments[0].value", inpElement);

Python 3

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
input_element = driver.findElement(By.ID, "inputTag")
value = input_element.execute_script("return arguments[0].value", input_element)

Upvotes: 2

alecxe
alecxe

Reputation: 474191

This is the input element - you need to get the value attribute:

webDriver.findElement(By.id("inputTag")).getAttribute("value")

Upvotes: 45

Related Questions