如何检查当前日期并移至下一个日期

2024-05-11

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

这个想法是定义一个可重用的函数 - 调用它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

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何检查当前日期并移至下一个日期 的相关文章

随机推荐

  • MongoDB 如何使用 $date 运算符进行查询?

    编辑 上下文 我正在使用 Talend ETL 工具 并在查询中使用 ISODate 或 Date 或 new Date 如下所示失败并出现错误 因此我需要解决方法 dt ISODate 2014 01 01 dt Date 2014 01
  • 正则表达式是否用于构建解析器?

    这只是出于好奇的一个问题 因为我最近需要越来越多地解析和使用正则表达式 似乎 对于我在搜索中遇到的有关某种解析的问题 有人总是最终说 当问一些与正则表达式相关的问题 正则表达式对此不好 请使用这样那样的解析器 因为我已经更好地理解了正则表达
  • 如何检查变量是否是生成器函数? (例如函数*产量)[重复]

    这个问题在这里已经有答案了 检查函数是否是生成器的可靠方法是什么 例如 let fn function yield 100 if fn instanceof for let value in fn 我能想到的唯一方法是fn toString
  • React:URL 配置文件 ID 不匹配 (match.params.id)

    所以每当我点击 查看个人资料 链接时 View Profile 它在 URL 中显示了良好配置文件的用户 ID 但每当我单击它以将其与此按钮匹配时 我都会收到错误 const Profile getProfileById match gt
  • GLSL 中的二阶函数?

    我正在寻找一种方法来使用一个函数作为 GLSL 中另一个函数的参数 在常规 C 中 可以通过传递函数指针作为函数参数来模拟它 似乎其他语言 如 HLSL 现在提供了处理高级构造 如高阶函数 的方法 或者可以使用以下命令来模拟它们巧妙利用 H
  • 防止别人使用我的dll

    我是 net 的新手 想知道如何防止其他人使用 引用我编译的库 我做了一些研究 但没有找到明确的答案 是authenticode还是强名称还是其他什么 它的可靠性如何 这些库是商业桌面软件的一部分 如何防止其他人使用我编译的库 我想知道如何
  • 当库静态链接时静态变量会发生什么

    假设我有图书馆 A 实现单例模式 它的实现中有一个静态变量 A 库被编译为静态库 现在 假设我的项目中有 B 另一个静态链接的静态库 A C 另一个静态链接的静态库 A D 一个顶级程序链接 B and C 最后 我的单例真的是单例 并且我
  • 如何从网站中抓取动态内容?

    所以我使用 scrapy 从亚马逊图书部分抓取数据 但不知何故我知道它有一些动态数据 我想知道如何从网站中提取动态数据 到目前为止我已经尝试过以下方法 import scrapy from items import AmazonsItem
  • Xcode 11 beta 4 错误:命令 CompileSwiftSources 失败,退出代码非零

    我已经下载了最新的 Xcode beta 4 当我构建时 我的 3 个 pod 遇到了同样的错误 Command CompileSwiftSources failed with a nonzero exit code
  • Xcode 4:获取请求模板变量?

    在 Xcode 3 X 中 您应该右键单击获取请求模板的谓词编辑器中的空白来指定变量输入而不是硬编码谓词 这是 XCode 4 中的哪里 我已经按住了选项 右键单击 选项单击等 但无法弄清楚 我认为X4不再有变量了 相反 我认为您必须选择一
  • env: python: 使用 Xcode 构建应用程序时没有这样的文件或目录

    当我在 Xcode 在 MacOS 12 3 上 中构建 运行 存档我的应 用程序时 遇到此错误 env python No such file or directory Command Ld failed with a nonzero e
  • Git:当文件位于嵌套 git 存储库中时强制“添加”

    我想添加一个包含在父存储库中的嵌套 git 存储库中的文件 我正在开发一个在我的项目中使用的库 然而git add nested repo myfile不做任何事情 我可以尝试重命名 git文件在进行提交时 但是当我重命名回时 我担心会出现
  • 未找到 ADB screenrecord 命令

    我无法奔跑adb shell screenrecord sdcard my mp4 我尝试运行此命令的设备规格 Honor 5C 安卓6 0 每当我运行 screenrecord 命令时 它都会显示未找到命令 D adb gt adb sh
  • Android 从图库中选择图像显示内存错误

    我正在编写一个代码示例 我必须从图库中选择一个图像 该代码正在运行 但是在从图库中选择图像后 我得到了内存不足错误 in my 活动结果时 我可以获得小图像 但大图像会产生问题 这是我的代码 try Uri selectedImageUri
  • Windows 中内存分配的限制+我计算得是否正确?

    我正在编写一个需要大量内存的程序 大型图形分析 目前我的程序中有两个主要的数据结构 占用了大部分内存 这些都是 n n 类型的矩阵int 和长度为 n 的数组 类型Node 在本例中 节点是一个包含两个 int 的结构体 sizeof No
  • Maven Pom.xml 问题

    我正在尝试使用 maven 制作一个 spring mvc 项目 并在 pom xml 中出现以下错误 CoreException 无法计算构建计划 插件 org apache maven plugins maven compiler pl
  • R 中的输出,避免写“[1]”

    I use print从 R 中的函数输出 例如 print blah blah blah 这输出 1 blah blah blah 到控制台 我怎样才能避免 1 和引号 Use cat Your string type cat查看帮助页面
  • Glassfish 3 有两种配置

    我想在 Glassfish 3 1 中设置 JDBC 领域 我正在关注这个博客http blog gamatam com 2009 11 jdbc realm setup with glassfish v3 html http blog g
  • ExtJS 4 用于选择所选值的组合框事件

    由于某种原因 我需要知道用户何时从组合框中选择了值 即使它已经被选择 仅当用户选择未选择的项目时 选择 事件才起作用 我在组合框或选择器的文档中没有看到任何类似 itemclick 的事件 有任何想法吗 ComboBox uses 绑定列表
  • 如何检查当前日期并移至下一个日期

    我遇到了一个我似乎无法理解的 python 问题 不确定是否需要使用 if 语句 但因为我是 python 新手 所以我实际上不确定如何编写这个小问题 事实上 这就是我遇到的问题 对于出发日历 我希望 python 能够执行以下操作 查看