157

In the HTML of a web application there is the following code:

<input type="text" name="prettyTime" id="prettyTime" class="ui-state-disabled prettyTime"  readonly="readonly">

A string displaying the time is actually shown on the page.

In Selenium WebDriver, I have a WebElement object referring to the <input> using:

WebElement timeStamp = waitForElement(By.id("prettyTime"));

I want to get the value of the WebElement, or, in other words, what is printed on the page. I tried all the WebElement getters and nothing has been retrieving the actual value that the user sees.

12 Answers 12

257

Try element.getAttribute("value")

The text property is for text within the tags of an element. For input elements, the displayed text is not wrapped by the <input> tag, instead it's inside the value attribute.

Note: Case matters. If you specify "Value", you'll get a 'null' value back. This is true for C# at least.

Sign up to request clarification or add additional context in comments.

10 Comments

getAttribute("value") is really how you do this?! That doesn't make any sense. There's a big difference between the value attribute of an input element and its value property. Does Selenium do the horrible thing jQuery does and conflate them?
getAttribute is documented by Selenium as first looking for a property, then fallbacking on attributes. So, it does the work. Now, there is getDomProperty, which is only about getting the property, and so, is a closer match for the need. I have added an answer about it.
That's what I've bumped into right now: trying to get a value from a textarea, which is neither a "value" attribute, nor a between-tag text (set dynamically as "value" attribute.
Well, it turns out that if the attribute is missing, it will try to get the corresponding property. So you can take a "value" from a textarea.
Apparently, this is the only way I managed to access angulat material form fields
For javascript users, don't forget the await when using getAttribute.
|
31

You can do it like this:

webelement time = driver.findElement(By.id("input_name")).getAttribute("value");

This will give you the time displaying on the webpage.

Comments

23

For Python bindings it will be:

element.get_attribute('value')

2 Comments

This is only answer that works for me! on Mac OSX + Python 3.7.7
In Ruby this is element['value']
18

With Selenium 2, I usually write it like this:

WebElement element = driver.findElement(By.id("input_name"));
String elementval = element.getAttribute("value");

Or

String elementval = driver.findElement(By.id("input_name")).getAttribute("value");

Comments

5

As was mentioned before, you could do something like this:

public String getVal(WebElement webElement) {
    JavascriptExecutor e = (JavascriptExecutor) driver;
    return (String) e.executeScript(String.format("return $('#%s').val();", webElement.getAttribute("id")));
}

But as you can see, your element must have an id attribute, and also, jQuery on your page.

Comments

5

Following ragzzy's answer, I use

public static string Value(this IWebElement element,
                           IJavaScriptExecutor javaScriptExecutor)
{
    try
    {
        string value = javaScriptExecutor.ExecuteScript("return arguments[0].value", element) as string;
        return value;
    }
    catch (Exception)
    {
        return null;
    }
}

It works quite well and does not alter the DOM.

Comments

4

Use

element.GetAttribute("value");

Even though if you don't see the "value" attribute in the HTML DOM, you will get the field value displayed in the GUI.

Comments

1

If the input value gets populated by a script that has some latency involved (e.g. AJAX call) then you need to wait until the input has been populated. E.g.

var w = new WebDriverWait(WebBrowser, TimeSpan.FromSeconds(10));
            w.Until((d) => {
                // Wait until the input has a value...

                var elements = d.FindElements(By.Name(name));

                var ele = elements.SingleOrDefault();

                if (ele != null)
                {
                    // Found a single element

                    if (ele.GetAttribute("value") != "")
                    {
                        // We have a value now
                        return true;
                    }
                }

                return false;
                });

        var e = WebBrowser.Current.FindElement(By.Name(name));

        if (e.GetAttribute("value") != value)
        {
            Assert.Fail("Result contains a field named '{0}', but its value is '{1}', not '{2}' as expected", name, e.GetAttribute("value"), value);
        }

Comments

1

Nowadays, use element.getDomProperty("value"). It is only about getting the property, and so, this is a closer match for the need than getAttribute. When asking for retrieving an input value, usually the developer wants the current value of the value property, which represents the current value of the input. While the DOM attribute value value will only be the initial value of the input element.

getAttribute is a mixed bag with a misleading name: it first attempts to retrieve a property current value if it exists, otherwise fallback on looking for a matching attribute. So, it works for the need of getting an input current value, but that is misleading, one may always ask whether that is truly correct or not.

If actually willing to get the value attribute value, not the property value, use getDomAttribute("value").

As said by others, getText is something else entirely. It is meant to retrieve the text content of an HTML tag. So, it applies only to tags which are not self-closing and can hold some text content, like <p>Some text content</p>. The value of an input is not text content.

Comments

0

Java users:

To get what is printed on the page, we need to use the getText() method.

getText() method

The getText() method returns the visible inner text of a web element.

getAttribute() method

On the other hand, the getAttribute() method fetches the value of the attribute we wish to retrieve.

Example:

<input name="Title" type="text" value="LambdaTest" /> Welcome to LambdaTest </input>

getText()

driver.findElement(By.name("Title")).getText();

Output of above code => Welcome to LambdaTest

getAttribute():

  1. driver.findElement(By.name("Title")).getAttribute("value");

    Output of above code => LambdaTest

  2. driver.findElement(By.name("Title")).getAttribute("type");

    Output of above code => text

Source: Difference between getText() And getAttribute() in Selenium WebDriver

1 Comment

<input /> is invalid in html, and same for <input> Welcome to LambdaTest </input>. Input is a self closing tag that is not allowed to have any child.
0

It works for me in java code:

@FindBy(how = How.XPATH, using = "//input[@formcontrolname='name']")
private WebElement name;

try {
      JavascriptExecutor jse;
      String value = (String)jse.executeScript("return arguments[0].value", name);
      return value;
    } catch(Exception ex) {
      return "";
    }

Comments

-4

This is kind of hacky, but it works.

I used JavascriptExecutor and added a div to the HTML, and changed the text in the div to $('#prettyTime').val()

I then used Selenium to retrieve the div and grab its value. After testing the correctness of the value, I removed the div that was just created.

1 Comment

This shouldn't be the accepted answer. Even if using JS, you can just execute and return that (instead of messing with the DOM).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.