Using Selenium WebDriver to retrieve the value of an HTML input
Asked Answered
C

11

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.

Clint answered 21/10, 2011 at 16:17 Comment(0)
C
-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.

Clint answered 26/10, 2011 at 18:42 Comment(1)
This shouldn't be the accepted answer. Even if using JS, you can just execute and return that (instead of messing with the DOM).Pavlodar
M
251

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.

Mccutcheon answered 21/10, 2011 at 19:33 Comment(8)
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?Stanch
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.Vesical
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.Vesical
Apparently, this is the only way I managed to access angulat material form fieldsKwasi
For javascript users, don't forget the await when using getAttribute.Heat
In Python, it would be get_attribute (with an underscore and all lowercase), not getAttribute (yes, this question is tagged with Java).Heredity
In C#, it is GetAttribute (capital "G"), not getAttribute.Heredity
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).Heredity
C
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.

Chaunceychaunt answered 18/6, 2014 at 12:19 Comment(0)
A
21

For Python bindings it will be:

element.get_attribute('value')
Adopt answered 5/6, 2018 at 9:44 Comment(2)
This is only answer that works for me! on Mac OSX + Python 3.7.7Sylph
In Ruby this is element['value']Biogeography
H
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");
Hinkel answered 28/3, 2013 at 22:6 Comment(0)
G
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.

Girder answered 25/3, 2014 at 9:45 Comment(0)
P
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.

Possession answered 9/8, 2016 at 15:26 Comment(0)
A
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.

Anglophile answered 23/3, 2020 at 18:20 Comment(0)
F
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);
        }
Frig answered 8/1, 2013 at 2:53 Comment(0)
W
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

Weswesa answered 3/8, 2021 at 9:55 Comment(1)
<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.Multiplication
G
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 "";
    }
Grave answered 26/10, 2023 at 21:25 Comment(0)
C
-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.

Clint answered 26/10, 2011 at 18:42 Comment(1)
This shouldn't be the accepted answer. Even if using JS, you can just execute and return that (instead of messing with the DOM).Pavlodar

© 2022 - 2024 — McMap. All rights reserved.