5

There's a hidden input field in which I'm trying to insert a specific date value. The field originally produces a value, from which a user can select an appropriate value. The page's source code looks like this:

<div id="change_img">
  <img width="80" height="30" border="1" src="http://jntuh.ac.in/results/images/CaptchaSecurityImages.php?width=100&height=50&characters=5&code=ryyrh">
  <br>
  <input id="code" type="hidden" value="ryyrh" name="code">
</div>

3 Answers 3

9

Use WebElement's getAttribute method. In your case it will be:

WebElement hiddenInput = driver.findElement(By.id("code"));
String value = hiddenInput.getAttribute("value");

If for any reason you need to do it with javascript (your question specifically asked for js) then this code should work:

String script = "return document.getElementById('code').getAttribute('value');";
String value = ((JavascriptExecutor) driver).executeScript(script).toString();
Sign up to request clarification or add additional context in comments.

2 Comments

I don't think you saw the question specifically was dealing with a hidden element. The first example on a hidden element will throw an exception and the second, even though it is perfectly legitimate javascript, will return null. If I'm missing something please let me know.
I usually try to verify my answers by running the code first. Hard to remember if I did it in this case as it was over a year ago. ;) Nevertheless I believe it's correct. I don't have Selenium installed on my machine right know but I've successfully executed the javascript both on a div with display: none style and on <input type='hidden' ... /> tag. I may be missing something though. Could you please provide example page and a reference to a tag on which the javascript provided returns null?
1

I tested this solution in C# and it works. I am then able to parse the returned string to find and verify what I need.

http://yizeng.me/2014/04/08/get-text-from-hidden-elements-using-selenium-webdriver/

So in the example in the question you would get the innerHTML of the visible parent "change_img" element which will include the hidden element.

Comments

-1

Solution in Python:

script = "return document.getElementById('code').getAttribute('value');";
print(driver.execute_script(script))

Solution in C#:

string script = "return document.getElementById('code').getAttribute('value');";
string value = ((IJavaScriptExecutor)driver).ExecuteScript(script).ToString();

Comments

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.