最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

selenium - how to get hidden values in webdriver using javascript - Stack Overflow

programmeradmin2浏览0评论

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=".php?width=100&height=50&characters=5&code=ryyrh">
  <br>
  <input id="code" type="hidden" value="ryyrh" name="code">
</div>

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>
Share Improve this question edited Oct 15, 2013 at 16:22 showdev 29.2k37 gold badges59 silver badges79 bronze badges asked Oct 15, 2013 at 15:56 Sunil KumarSunil Kumar 731 gold badge1 silver badge8 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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();

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.

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();
发布评论

评论列表(0)

  1. 暂无评论