Selenium(Python):如何在隐藏输入上插入值? [英] Selenium (Python): How to insert value on a hidden input?
问题描述
我正在使用Selenium的WebDriver并使用Python编码。
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"/>
其中 value =2013-11-26
是我试图注入一个值的字段(它原来是空的,即: value =
。
where value="2013-11-26"
is the field I'm trying to inject a value (it's originally empty, ie: value=""
.
据我所知,WebDriver无法在隐藏输入中插入值,因为普通用户无法在浏览器中执行此操作,但解决方法是使用Javascript。不幸的是,这是一种我不熟悉的语言有人知道会起作用吗?
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?
推荐答案
你可以使用 WebDriver.execute_script
。例如:
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')
更新
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))
这篇关于Selenium(Python):如何在隐藏输入上插入值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!