How to change the date of a hidden element of a Datepicker using setAttribute method and Selenium with Python?

杀马特。学长 韩版系。学妹 提交于 2021-02-02 09:25:28

问题


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.

My script looks like this:

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

and

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

The HTML code and picture of the website looks like this:

HTML of date picker: HTML code of date picker

Date picker element:

Date picker

Edit:

Updated HTML with the hidden element visible


回答1:


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:

  • How to Change a html line code with python
  • Selenium Datepicker using JavascriptExecutor
  • Is there a way to add a new attribute with a value to an element using selenium python?


来源:https://stackoverflow.com/questions/65064715/how-to-change-the-date-of-a-hidden-element-of-a-datepicker-using-setattribute-me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!