151

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jamesfzhang
  • 4,403
  • 8
  • 32
  • 43

10 Answers10

250

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.

GrayDwarf
  • 2,469
  • 2
  • 20
  • 22
prestomanifesto
  • 12,528
  • 5
  • 34
  • 50
  • 16
    `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? – T.J. Crowder Jul 07 '16 at 18:12
  • 1
    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. – C-F Jun 05 '17 at 22:03
  • 2
    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. – C-F Jun 05 '17 at 22:11
  • Apparently, this is the only way I managed to access angulat material form fields – Yennefer Mar 07 '19 at 08:47
  • For javascript users, don't forget the `await` when using `getAttribute`. – Jeffrey Martinez May 20 '20 at 19:28
  • In Python, it would be [`get_attribute`](https://www.selenium.dev/documentation/webdriver/elements/finders/#tabs-10-1) (with an underscore and all lowercase), not `getAttribute` (yes, this question is tagged with Java). – Peter Mortensen Mar 28 '22 at 23:58
  • In C#, it is [`GetAttribute`](https://www.selenium.dev/documentation/webdriver/elements/finders/#tabs-10-1) (capital "G"), not `getAttribute`. – Peter Mortensen Mar 28 '22 at 23:59
  • As this is very confusing, with *different* names for Java, Python, C#, Ruby, JavaScript, and Kotlin, perhaps list the different names in the answer? Or at least make it very clear that "getAttribute" is only for Java (and happens to be the same for JavaScript and Kotlin). – Peter Mortensen Mar 29 '22 at 00:04
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Praveen
  • 378
  • 3
  • 6
21

For Python bindings it will be:

element.get_attribute('value')
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sajid Manzoor
  • 487
  • 1
  • 5
  • 9
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");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
e1che
  • 1,241
  • 1
  • 17
  • 34
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
raggzy
  • 81
  • 1
  • 3
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vfleitao
  • 58
  • 3
  • 12
3

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Rajesh
  • 29
  • 4
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);
        }
saille
  • 9,014
  • 5
  • 45
  • 57
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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 1
    is invalid in html, and same for Welcome to LambdaTest . Input is a self closing tag that is not allowed to have any child. – Xinchao Jan 18 '22 at 05:10
-3

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jamesfzhang
  • 4,403
  • 8
  • 32
  • 43
  • 18
    This shouldn't be the accepted answer. Even if using JS, you can just execute and return that (instead of messing with the DOM). – Matt Luongo Jul 01 '16 at 00:14