我遇到了一个我似乎无法理解的 python 问题。不确定是否需要使用 if 语句,但因为我是 python 新手,所以我实际上不确定如何编写这个小问题。
事实上,这就是我遇到的问题。对于出发日历,我希望 python 能够执行以下操作:
- 查看“你的约会对象”。如果有航班(无论是廉价航班还是普通航班),请单击它。如果没有,则转到下一个有航班的可用日期并单击该日期。
- 如果当前月份没有可用日期,则需要能够移至下个月(我有一个示例代码)。
对于返程日历,我希望它执行相同的操作,但确保它选择所选出发日期后至少 7 天的日期。
这实际上是我的问题,该怎么做?
下面是出发日历的 html(回程日历完全相同,只是它是入站搜索结果而不是出站搜索结果):
下面我有一个示例代码,如果您想使用该模板并对其进行操作,则可以在从普通日期选择器(在 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