简体   繁体   中英

How to Automate datepicker in python selenium?

I need to search for a flight with python selenium but I couldn't able to select my desirable date.

import time
import selenium
from selenium import webdriver

browser = webdriver.Chrome()
browser.get("https://www.spicejet.com/")

departureButton = browser.find_element_by_id("ctl00_mainContent_ddl_originStation1_CTXT")

departureButton.click()
browser.find_element_by_partial_link_text("Kolkata").click()

arivalButton = browser.find_element_by_id("ctl00_mainContent_ddl_destinationStation1_CTXT")
arivalButton.click()
browser.find_element_by_partial_link_text("Goa").click()

date_position = browser.find_element_by_id("ctl00_mainContent_view_date1")
date_position.click()

search_date = "10-September 2019"
dep_date1 = search_date.split("-")

    dep_month = dep_date[1]
dep_day = dep_date[0]
cal_head = browser.find_elements_by_class_name("ui-datepicker-title")
for month_hd in cal_head:
    month_year = month_hd.text
    if dep_month == month_year:
        pass
    else:
        nxt = browser.find_element_by_class_name("ui-icon-circle-triangle-e").click()

    print(month_year) 
time.sleep(2)
browser.close()

The problem with your code is that when you click on the next button the DOM changes and the element reference saved in your variables are not updated. That is why it gives you stale element reference exception. Instead of using variables, use the locator for every time you access the calendar elements and it will work.

Try This :

import time
import selenium
from selenium import webdriver

browser = webdriver.Chrome()
browser.get("https://www.spicejet.com/")

departureButton = browser.find_element_by_id("ctl00_mainContent_ddl_originStation1_CTXT")

departureButton.click()
browser.find_element_by_partial_link_text("Kolkata").click()

arivalButton = browser.find_element_by_id("ctl00_mainContent_ddl_destinationStation1_CTXT")
arivalButton.click()
browser.find_element_by_partial_link_text("Goa").click()

date_position = browser.find_element_by_id("ctl00_mainContent_view_date1")
date_position.click()

search_date = "10-September 2019"
dep_date = search_date.split("-")

dep_month = dep_date[1]
dep_day = dep_date[0]

while browser.find_element_by_class_name("ui-datepicker-title").text != dep_month:
    browser.find_element_by_css_selector("a[data-handler='next']").click()

browser.find_element_by_xpath("//table//a[text()='"+dep_day+"']").click()


time.sleep(2)
browser.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM