You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用SeleniumBase选择日历中的可用日期?

修正SeleniumBase中选择可用日历日期的CSS选择器问题

问题根源

你当前Pick_available_date函数里的CSS选择器写法存在两个关键错误:

  • 多类名的CSS选择器需要用.连接(表示元素同时拥有这些类),而不是空格(空格代表后代元素关系)
  • 硬编码了fc-day-fri(周五)类,限制只能选择周五的日期,不符合“任意可用日期”的需求

根据你给出的规则:可用日期的td标签同时拥有fc-day-future和date-availiable类,必须调整选择器匹配这两个类的交集。

修正后的代码

先补充缺失的sleep导入,再修改选择器并优化等待逻辑:

from seleniumbase import SB
from time import sleep  # 补充sleep模块导入

def open_the_form_turnstile_page(sb):
    sb.driver.uc_open_with_reconnect(
        "https://localhost", reconnect_time=12,
    )

# Captcha Check
def click_turnstile_and_verify(sb):
    # sb.driver.uc_switch_to_frame("iframe") #Enable it if the Captcha not check automatic
    # sb.driver.uc_click("span.mark")
    sb.highlight('/html/body/app-root/div/div/app-login/section/div/div/mat-card/form/app-cloudflare-captcha-container/div', timeout=3.33)
    print("Captcha Check >>>>>>> Success")
    sleep(5)

def Pick_available_date(sb):
    # 修正选择器:匹配同时拥有fc-day-future和date-availiable类的td元素
    available_date_selector = "td.fc-day-future.date-availiable"
    # 显式等待元素加载完成,避免因日历未渲染导致的点击失败
    sb.wait_for_element_visible(available_date_selector, timeout=10)
    sb.click(available_date_selector)
    print("Time Slots click >>>>>>> Success") 
    sb.highlight_click('a:contains("Select")')
    print("Select Button click >>>>>>> Success") 
    sleep(2) 
    return Review(sb)  # 需确保Review函数已提前定义

# 主执行逻辑
with SB(uc=True, demo=True) as sb:
    while True:
        try:
            open_the_form_turnstile_page(sb)
            click_turnstile_and_verify(sb)
            Pick_available_date(sb)
        except Exception as e:
            print(f'error encountered: {e}')
        finally:        
            sleep(2)
            sb.quit()  # 修正为SeleniumBase官方API的退出方式

额外优化建议

  1. 移除特定星期类:彻底去掉fc-day-fri这类硬编码的星期类,确保能选择所有符合条件的可用日期
  2. 替换sleep为显式等待:尽可能用sb.wait_for_element_clickable等API代替固定时长的sleep,提升代码稳定性
  3. 支持随机选择多可用日期:如果页面存在多个可用日期,可随机选择其中一个:
available_dates = sb.find_elements(available_date_selector)
if available_dates:
    import random
    random.choice(available_dates).click()

内容的提问来源于stack exchange,提问作者Saber Abd ElHalim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 04:35:25