日历点击遇Stale Element Reference错误及间隔点击需求排查
解决日历点击时的Stale Element错误并实现隔天点击逻辑
错误原因
点击日期后执行ShowBtn和BackBtn操作时,页面DOM大概率发生了局部刷新或元素重新渲染,导致最初一次性获取的days列表里的WebElement实例失效,后续循环操作这些元素就会触发stale element reference: stale element not found错误。
解决方案
核心思路是每次循环时重新定位日期元素,避免复用失效的元素引用;同时通过索引判断实现“点击第一天、跳过第二天、点击第三天”的循环逻辑。
修改后代码
public void GetData(WebDriver driver, String userYear) { // 先获取当月有效日期的总数 List<WebElement> currentMonthDays = getCurrentMonthDays(driver, userYear); int totalDays = currentMonthDays.size(); for (int i = 0; i < totalDays; i++) { // 每次循环重新获取最新的当月日期元素,避免stale引用 currentMonthDays = getCurrentMonthDays(driver, userYear); WebElement day = currentMonthDays.get(i); String dayText = day.getText(); // 实现点击第1、3、5...天的逻辑(索引0、2、4对应第一天、第三天...) if (i % 2 == 0) { System.out.println("点击日期:" + dayText); day.click(); // 可选:添加显式等待,确保页面加载完成后再执行后续操作 new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(locators.getShowBtnLocator(userYear))); ShowBtn(userYear); new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(locators.getBackBtnLocator(userYear))); BackBtn(userYear); } else { System.out.println("跳过日期:" + dayText); } } } // 辅助方法:过滤出当月的有效日期元素(排除前后月份的灰色日期) private List<WebElement> getCurrentMonthDays(WebDriver driver, String userYear) { List<WebElement> allDays = locators.getLocationOfTheDays(divPathSelector(userYear)); List<WebElement> currentMonthDays = new ArrayList<>(); for (WebElement day : allDays) { // 根据实际页面的class属性判断是否为当月日期,示例为排除含prev/next-month类的元素 String dayClass = day.getAttribute("class"); if (!dayClass.contains("prev-month") && !dayClass.contains("next-month")) { currentMonthDays.add(day); } } return currentMonthDays; }
关键说明
- 重新定位元素:每次循环都调用
getCurrentMonthDays获取最新的日期元素列表,确保元素引用始终有效,规避Stale Element错误。 - 隔天点击逻辑:通过
i % 2 == 0判断索引,只处理偶数索引的元素(对应第一天、第三天等奇数日期),奇数索引直接跳过。 - 过滤无效日期:日历通常会显示前后月份的灰色日期,辅助方法通过class属性过滤这些无效元素,确保只处理当月日期。
- 显式等待:在点击后添加显式等待,保证页面元素加载完成再执行后续操作,提升代码稳定性。
内容的提问来源于stack exchange,提问作者samet mete
相关产品推荐
相关产品推荐

