问题
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:
Date picker element:
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