Home > Enterprise >  How to click on calendar icon on date field and select date using Selenium Python
How to click on calendar icon on date field and select date using Selenium Python

Time:08-04

I am new to selenium, and I am stuck in one scenario where I am not able to click on calendar Icon as shown in this snapshot.

enter image description here

Below is the html code, please help me to click the calendar icon. It seems from code that date text field and icon are same, but in actual these both are differently clickable.

<div >
Date
<span >*</span>
<input required="" type="Date" min="2020-01-01" max="2022-08-03" id="logEffortfromDate"  style="cursor: text;">
<span >
</span>
</div>

Once the calendar is open select on any date. But calendar is not mention in inspect html code.

The reason why I am not using send_keys() is that the url do not respond properly if date entered directly.

CodePudding user response:

While there are some acrobatics in selenium to click on the input, scroll years/months, click on day, you might be able to setup the date (given it's an input with a value) by setting the value attribute directly. So something like this:

date_input = WebDriverWait(browser,5).until(EC.element_to_be_clickable((By.ID, 'logEffortfromDate')))
date_input.click()
t.sleep(1)
browser.execute_script('arguments[0].value = "2022-07-03";', date_input)

You will also need the following imports:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

Selenium documentation can be found at https://www.selenium.dev/documentation/

CodePudding user response:

Instead of clicking the calendar icon and selecting the date as an alternative you can set the date in the calendar as follows:

element = driver.find_element(By.XPATH, "//input[@id='logEffortfromDate']")
driver.execute_script("arguments[0].removeAttribute('type')", element)
new_element = driver.find_element(By.XPATH, "//input[@id='logEffortfromDate']")
driver.execute_script("arguments[0].setAttribute('value','02/08/2022')", new_element)
  • Related