使用Selenium 4.4与Python 3.10.6实现日历次日点击功能求助
修正后的代码及说明
问题分析
原代码的核心错误:
click()方法返回None,因此select_today_first是无效值,后续用(None,1)作为定位器完全不符合Selenium语法- 过度依赖硬编码的
time.sleep,稳定性极差 - 未正确定位日历中的次日元素
修正方案
采用显式等待替代隐式等待+固定sleep,通过两种可靠方式定位次日日期:
方法1:通过日期文本直接定位(推荐,稳定性更高)
先计算次日的日期字符串,再精准匹配日历上的日期按钮文本:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from datetime import datetime, timedelta # 初始化浏览器驱动(根据你的浏览器类型调整,比如Chrome/Firefox) driver = webdriver.Chrome() # 计算次日日期,格式要和日历显示的文本一致: # 若日历仅显示日数(如"25")用"%d",显示完整日期(如"2024-05-25")用"%Y-%m-%d" next_day_text = (datetime.today() + timedelta(days=1)).strftime("%d") # 打开目标页面(替换为你的实际页面URL) driver.get("你的目标页面地址") # 点击日期选项,触发日历弹窗 WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, 'input_27')) ).click() # 展开日历控件 WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, 'input_60')) ).click() # 定位并点击次日日期按钮(需根据实际HTML调整class名称) next_day_btn = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, f"//button[contains(@class, 'dtp-date') and text()='{next_day_text}']")) ) next_day_btn.click() # 点击确认按钮完成选择 WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.CSS_SELECTOR, 'button.dtp-btn-ok.md-button.md-button.md-ink-ripple')) ).click() # 后续操作... driver.quit()
方法2:通过今日元素的相对定位
如果日历是按顺序排列的,找到已选中的今日元素后,点击其下一个兄弟元素:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Chrome() driver.get("你的目标页面地址") # 打开日期选项和日历控件 WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, 'input_27'))).click() WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, 'input_60'))).click() # 点击"今日"按钮,让日历定位到今日 WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.CSS_SELECTOR, 'button.dtp-btn-today.md-button.md-button.ng-scope.md-ink-ripple')) ).click() # 找到当前选中的今日元素(假设选中后有dtp-active类),再定位其下一个兄弟日期按钮 today_btn = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CSS_SELECTOR, 'button.dtp-date.dtp-active')) ) next_day_btn = today_btn.find_element(By.XPATH, "./following-sibling::button") next_day_btn.click() # 点击确认按钮 WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.CSS_SELECTOR, 'button.dtp-btn-ok.md-button.md-button.md-ink-ripple')) ).click() driver.quit()
关键注意事项
- 必须根据实际页面的HTML结构调整定位器:比如日期按钮的class名称、文本格式、兄弟元素的层级关系等
- 用
WebDriverWait显式等待替代time.sleep,能大幅提升代码稳定性 - 若今日是月底,次日属于下月,需要额外判断并添加月份切换的逻辑
内容的提问来源于stack exchange,提问作者Ahmed Hesham
相关产品推荐
相关产品推荐

