如何使用setAttribute方法和Selenium与Python更改Datepicker的隐藏元素的日期? [英] How to change the date of a hidden element of a Datepicker using setAttribute method and Selenium with Python?
问题描述
我一直在努力寻找一种使用Selenium和Python设置日期选择器日期的方法.我发现有一个带有日期的隐藏元素,所以我尝试用javascript executor为该隐藏元素设置一个值.我尝试了不同的方法,脚本似乎可以很好地执行,但是日期没有改变.
I have been struggling for days to find a way to set a date of a datepicker using Selenium with Python. I found out that there is a hidden element with the date, so I tried javascript executor to set a value to that hidden element. I tried different ways, and the scripts seem to execute fine, but the date doesn't change.
我的脚本如下:
#input date by using hidden date method 1
element = browser.find_element_by_xpath("/html[1]/body[1]/div[1]/form[1]/table[1]/tbody[1]/tr[1]/td[1]/div[1]/table[1]/tbody[1]/tr[2]/td[1]/div[1]/table[1]/tbody[1]/tr[1]/td[1]/table[1]/tbody[1]/tr[2]/td[1]/table[1]/tbody[1]/tr[1]/td[2]/input[1]")
browser.execute_script("arguments[0].setAttribute('value', '{0}')".format("2019-10-31"), element )
element.submit()
和
#input date by using hidden date method 2
date = "2019-10-31"
element= browser.find_element_by_xpath("/html[1]/body[1]/div[1]/form[1]/table[1]/tbody[1]/tr[1]/td[1]/div[1]/table[1]/tbody[1]/tr[2]/td[1]/div[1]/table[1]/tbody[1]/tr[1]/td[1]/table[1]/tbody[1]/tr[2]/td[1]/table[1]/tbody[1]/tr[1]/td[2]/input[1]")
browser.execute_script('arguments[0].setAttribute("value", "%s")' % date, element)
element.submit()
网站的HTML代码和图片如下:
The HTML code and picture of the website looks like this:
日期选择器的HTML:
HTML of date picker:
日期选择器元素:
更新后的HTML具有可见的隐藏元素
Updated HTML with the hidden element visible
推荐答案
< input>
元素的 type 属性设置为隐藏强>.您可以编辑/删除 type 属性,并按如下所示设置值:
The <input>
element is having the type attribute set as hidden. You can edit/remove the type attribute and set the value as follows:
element = browser.find_element_by_xpath("/html[1]/body[1]/div[1]/form[1]/table[1]/tbody[1]/tr[1]/td[1]/div[1]/table[1]/tbody[1]/tr[2]/td[1]/div[1]/table[1]/tbody[1]/tr[1]/td[1]/table[1]/tbody[1]/tr[2]/td[1]/table[1]/tbody[1]/tr[1]/td[2]/input[1]")
browser.execute_script("arguments[0].removeAttribute('type')", element)
new_element = browser.find_element_by_xpath("/html[1]/body[1]/div[1]/form[1]/table[1]/tbody[1]/tr[1]/td[1]/div[1]/table[1]/tbody[1]/tr[2]/td[1]/div[1]/table[1]/tbody[1]/tr[1]/td[1]/table[1]/tbody[1]/tr[2]/td[1]/table[1]/tbody[1]/tr[1]/td[2]/input[1]")
browser.execute_script("arguments[0].setAttribute('value','2019-10-31')", new_element)
参考文献
您可以在以下位置找到几个相关的详细讨论:
References
You can find a couple of relevant detailed discussions in: