Selenium (Python): How to insert a value into hidden input?

I am using Selenium WebDriver and coding in Python.

There is a hidden input field in which I try to insert a specific date value. First, a calendar is initially created from which the user can select a suitable date, but this seems like a more complicated attempt to emulate than directly nesting the corresponding date value.

The source code of the page is as follows:

<div class="dijitReset dijitInputField">
<input id="form_date_DateTextBox_0" class="dijitReset" type="text" autocomplete="off" dojoattachpoint="textbox,focusNode" tabindex="0" aria-required="true"/>
<input type="hidden" value="2013-11-26" sliceindex="0"/>

where value="2013-11-26"- a field in which I try to enter a value (which is initially empty, ie: value="".

I understand that WebDriver cannot insert a value into hidden input because ordinary users cannot do this in the browser, but using Javascript is a workaround. Unfortunately, this is a language that I am not familiar with. Does anyone know what will work?

+4
source share
1 answer

You can use WebDriver.execute_script. For example:

from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://jsfiddle.net/falsetru/mLGnB/show/')
elem = driver.find_element_by_css_selector('div.dijitReset>input[type=hidden]')
driver.execute_script('''
    var elem = arguments[0];
    var value = arguments[1];
    elem.value = value;
''', elem, '2013-11-26')

UPDATE

from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://matrix.itasoftware.com/')
elem = driver.find_element_by_xpath(
    './/input[@id="ita_form_date_DateTextBox_0"]'
    '/following-sibling::input[@type="hidden"]')

value = driver.execute_script('return arguments[0].value;', elem)
print("Before update, hidden input value = {}".format(value))

driver.execute_script('''
    var elem = arguments[0];
    var value = arguments[1];
    elem.value = value;
''', elem, '2013-11-26')

value = driver.execute_script('return arguments[0].value;', elem)
print("After update, hidden input value = {}".format(value))
+6
source

All Articles