如何查看当前日期并转到下一个日期

时间:2016-02-07 17:15:20

标签: python python-2.7 selenium selenium-webdriver

我有一个我似乎无法理解的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

1 个答案:

答案 0 :(得分:1)

这个想法是定义一个可重用的函数 - 称它为select_date(),它接收一个“日历”WebElement和一个可选的最小日期。此函数首先在日历中查找Your date,如果它在那里并且超过最小值(如果给定),请单击它并返回日期。如果没有Your date,请查找可用的“航班”日期,如果给出最短日期且日期大于或等于,请点击它并返回日期。

工作实施:

from datetime import datetime, timedelta

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


def select_date(calendar, mininum_date=None):
    try:
        # check if "Your Date" is there
        your_date_elm = calendar.find_element_by_class_name("your-date")

        your_date = your_date_elm.get_attribute("data-date")
        print("Found 'Your Date': " + your_date)
        your_date_elm.click()

        # check if your_date against the minimum date if given
        your_date = datetime.strptime(your_date, "%Y-%m-%d")
        if mininum_date and your_date < mininum_date:
            raise NoSuchElementException("Minimum date violation")
        return your_date
    except NoSuchElementException:
        flight_date = None
        flight_date_elm = None
        while True:
            print("Processing " + calendar.find_element_by_css_selector("div.subheader > p").text)

            try:
                if mininum_date:
                    flight_date_elms = calendar.find_elements_by_class_name("flights")
                    flight_date_elm = next(flight_date_elm for flight_date_elm in flight_date_elms
                                           if datetime.strptime(flight_date_elm.get_attribute("data-date"), "%Y-%m-%d") >= mininum_date)
                else:
                    flight_date_elm = calendar.find_element_by_class_name("flights")
            except (StopIteration, NoSuchElementException):
                calendar.find_element_by_partial_link_text("Next month").click()

            # if found - print out the date, click and exit the loop
            if flight_date_elm:
                flight_date = flight_date_elm.get_attribute("data-date")
                print("Found 'Flight Date': " + flight_date)
                flight_date_elm.click()
                break

        return datetime.strptime(flight_date, "%Y-%m-%d")


driver = webdriver.Firefox()
driver.get("http://www.jet2.com/cheap-flights/leeds-bradford/antalya/2016-03-01/2016-04-12?adults=2&children=2&infants=1&childages=4%2c6")

wait = WebDriverWait(driver, 10)

# get the outbound date
outbound = wait.until(EC.visibility_of_element_located((By.ID, "outboundsearchresults")))
outbound_date = select_date(outbound)

# get the inbound date
inbound = driver.find_element_by_id("inboundsearchresults")
inbound_minimum_date = outbound_date + timedelta(days=7)
inbound_date = select_date(inbound, mininum_date=inbound_minimum_date)

print(outbound_date, inbound_date)

driver.close()

对于问题URL中提供的内容,它会打印:

Processing March 2016
Found 'Flight Date': 2016-03-28

Processing April 2016
Found 'Flight Date': 2016-04-04

2016-03-28 00:00:00 2016-04-04 00:00:00

最后打印的两个日期是出发日期和返回日期。

如果您需要任何澄清并希望它有所帮助,请告诉我。