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

使用Selenium在指定网站日历控件选择2021年12月1日失败求助

解决Selenium日历控件日期选择错误问题

问题原因

  • 你直接通过固定ID定位日期元素,但日历控件默认显示的并非目标年月(2021年12月),而是当前/最近的月份(如2022年8月),导致点击的是错误月份的日期。
  • 日历控件的日期元素ID是动态生成的,随月份变化,固定ID定位不可靠。

修正方案

通过动态切换年月+显式等待的方式定位目标日期,步骤如下:

  1. 等待日历弹出按钮加载完成并点击
  2. 循环切换年月,直到显示2021年12月
  3. 定位并点击1号日期

修正后的代码

# 先安装依赖(如果未安装)
# pip install selenium

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

path = "C:\\Program Files\\chromedriver.exe"
driver = webdriver.Chrome(path)
driver.get("https://www.cbe.org.eg/en/Auctions/Pages/AuctionsEGPTBillsHistorical.aspx")
driver.maximize_window()

wait = WebDriverWait(driver, 10)

# 点击日历弹出按钮
from_date_btn = wait.until(EC.element_to_be_clickable((By.ID, "ctl00_ctl54_g_1eef16cc_149b_4250_b1db_366c6f7aa7e6_imgFromPopup")))
from_date_btn.click()

# 目标年月
target_year_month = "December 2021"

# 循环切换到目标年月
while True:
    current_year_month = wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "ms-acal-month"))).text
    if current_year_month == target_year_month:
        break
    # 点击上一月按钮(如果当前年月晚于目标,点击左箭头)
    prev_btn = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "ms-acal-prev")))
    prev_btn.click()
    time.sleep(0.5)  # 短暂等待页面加载

# 定位并点击1号日期
target_day = wait.until(EC.element_to_be_clickable((By.XPATH, "//td[contains(@class, 'ms-acal-day') and text()='1']")))
target_day.click()

代码说明

  • 显式等待:使用WebDriverWait确保元素可交互,避免因页面加载慢导致的元素找不到问题。
  • 动态切换年月:通过对比当前显示的年月与目标年月,循环点击上一月按钮,直到切换到2021年12月。
  • 通用日期定位:使用XPath通过文本定位1号日期,避免依赖动态生成的ID,提升稳定性。

内容的提问来源于stack exchange,提问作者M_william

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 09:33:20