I have this minimal html:
<!DOCTYPE html>
<html>
<body>
<input type="date" max="2023-03-09" value="2023-03-09" onkeydown="return false">
</body>
</html>
That just asks for a date, but onkeydown="return false"
prevents keyboard input. So I have to navigate the (I guess browser-generated) calendar, but don’t know how to access it. Even the calendar icon in the control is difficult to access. I have resorted to clicking with a fixed offset, but maybe there’s a better way.
My minimal python code is:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
import time
driver = webdriver.Firefox()
driver.get("E:\Web\TestDate\public_html\index.html")
buttonDate = driver.find_element(By.TAG_NAME, "input")
action = ActionChains(driver)
w, h = buttonDate.size['width'], buttonDate.size['height']
x, y = buttonDate.location['x'], buttonDate.location['y']
wx, wy = driver.get_window_size()['width'], driver.get_window_size()['height']
action.move_to_element_with_offset(buttonDate, w - 10, h - 7)
action.click()
action.perform()
time.sleep(30)
driver.quit()
With that I can get the calendar control open, but cannot use send_keys()
to change the date.
4
Answers
just remove the event handler
Javascript code
full code such as
Online Test via jsfiddle
You can use Selenium’s
execute_script
method to runJavaScript
and pass the text into the desired textbox. Refer the code below:Note: This is like inserting the text into the web page from backend. This solution won’t imitate the human actions as selenium’s
send_keys
does.Given the HTML:
To send a customized date you can use the
removeAttribute()
method to remove the onkeydown attribute and invokesend_keys()
as follows:Browser snapshot:
References
You can find a couple of relevant detailed discussions in:
You can use the JS
setAttribute()
function to change the date directly: