Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

javascript - Selenium (Python): How to insert value on a hidden input?

I'm using Selenium's WebDriver and coding in Python.

There's a hidden input field in which I'm trying to insert a specific date value. The field originally produces a calendar, from which a user can select an appropriate date, but that seems like a more complicated endeavour to emulate than inserting the appropriate date value directly.

The page's source code looks like this:

<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" is the field I'm trying to inject a value (it's originally empty, ie: value="".

I understand that WebDriver is not able to insert a value into a hidden input, because regular users would not be able to do that in a browser, but a workaround is to use Javascript. Unfortunately that's a language I'm not familiar with. Would anyone know what would work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...