我遇到了一個我似乎無法理解的python問題。不知道我是否需要使用if語句,但是因爲我是python新手,我實際上並不確定如何編寫這個小問題。如何查看當前日期並移至下一日期
事實上,這是我的問題。對於出發日歷,我希望python能夠執行以下操作:
- 查看「您的日期」。如果有航班(低價或正常無關緊要),請點擊它。如果沒有,則轉到下一個有空位的日期,然後點擊該日期。
- 如果在當月沒有可用的日期,我需要能夠移動到下個月(我有一個示例代碼)。
對於返回日曆,我希望它做同樣的事情,但要確保它在選擇的出發日期後至少7天選擇一個日期。
這幾乎是我的問題,該怎麼做?
下面是depature日曆的HTML(回曆是完全一樣的,除了它是inboundsearchresults而不是對外的搜索結果):
下面我有一個示例代碼從一個普通的日期選擇器選擇時的工作(這在頁面中使用的URL之前),如果你想使用模板和操縱它:
# select depart date
datepicker = driver.find_element_by_id("departure-date-selector")
actions.move_to_element(datepicker).click().perform()
# find the calendar, month and year picker and the current date
calendar = driver.find_element_by_id("departureDateContainer")
month_picker = Select(calendar.find_element_by_class_name("ui-datepicker-month"))
year_picker = Select(calendar.find_element_by_class_name("ui-datepicker-year"))
current_date = calendar.find_element_by_class_name("ui-datepicker-current-day")
# printing out current date
month = month_picker.first_selected_option.text
year = year_picker.first_selected_option.text
print("Current departure date: {day} {month} {year}".format(day=current_date.text, month=month, year=year))
# see if we have an available date in this month
try:
next_available_date = current_date.find_element_by_xpath("following::td[@data-handler='selectDay' and ancestor::div/@id='departureDateContainer']")
print("Found an available departure date: {day} {month} {year}".format(day=next_available_date.text, month=month, year=year))
next_available_date.click()
except NoSuchElementException:
# looping over until the next available date found
while True:
# click next, if not found, select the next year
try:
calendar.find_element_by_class_name("ui-datepicker-next").click()
except NoSuchElementException:
# select next year
year = Select(calendar.find_element_by_class_name("ui-datepicker-year"))
year.select_by_visible_text(str(int(year.first_selected_option.text) + 1))
# reporting current processed month and year
month = Select(calendar.find_element_by_class_name("ui-datepicker-month")).first_selected_option.text
year = Select(calendar.find_element_by_class_name("ui-datepicker-year")).first_selected_option.text
print("Processing {month} {year}".format(month=month, year=year))
try:
next_available_date = calendar.find_element_by_xpath(".//td[@data-handler='selectDay']")
print("Found an available departure date: {day} {month} {year}".format(day=next_available_date.text, month=month, year=year))
next_available_date.click()
break
except NoSuchElementException:
continue
完美,我有很多東西要在短時間內學習,但是用你的腳本,我可以用它來幫助操縱我擁有的其他腳本。後來還有一個障礙需要處理,可能需要稍後再請求你的幫助,但同時,非常感謝你:) – BruceyBandit
@BruceyBandit很高興看到你正在進行更深入的測試自動化。讓我知道你是否需要進一步的幫助。 – alecxe