Selenium Java:日期选择器值转字符串失败问题求助
问题分析与解决
核心问题
- 日期值获取方式错误:Kendo UI的DateTimePicker输入框的实际日期值存储在
value属性中,而非元素的文本内容,所以getText()返回空字符串。 - 日期格式化调用错误:
fullDate.getText().format(...)的用法完全错误,你把DateTimeFormatter的内部占位符信息当成了格式化参数,导致输出了奇怪的Value(...)内容。
修正后的代码
public void dateExample() throws InterruptedException { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); String baseURL = "https://demos.telerik.com/kendo-ui/datetimepicker/index"; driver.get(baseURL); driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)); WebElement selectDate = driver.findElement(By.xpath("//button[@aria-label='Open the date view']")); selectDate.click(); WebElement midButn = driver.findElement(By.xpath("//a[@title='Navigate to year view']")); midButn.click(); WebElement previousBtn = driver.findElement(By.xpath("//a[@aria-label='Previous']")); previousBtn.click(); WebElement nextBtn = driver.findElement(By.xpath("//a[@aria-label='Next']")); nextBtn.click(); Thread.sleep(1000); nextBtn.click(); Thread.sleep(1000); WebElement pickMonth = driver.findElement(By.xpath("//a[@aria-label='July']")); pickMonth.click(); WebElement pickDay = driver.findElement(By.xpath("//a[@title='Monday, July 17, 2023']")); pickDay.click(); // 关键修正:通过value属性获取日期字符串 WebElement fullDate = driver.findElement(By.id("datetimepicker")); String dateStr = fullDate.getAttribute("value"); System.out.println("Full date is: " + dateStr); // 拆分日期部分 String[] dateParts = dateStr.split(" ")[0].split("/"); System.out.println("This is the Month " + dateParts[0]); System.out.println("This is the day " + dateParts[1]); System.out.println("This is the year " + dateParts[2]); // 可选:用DateTimeFormatter规范格式化日期 DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy h:mm a"); LocalDateTime dateTime = LocalDateTime.parse(dateStr, inputFormatter); DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm a"); String formattedDate = outputFormatter.format(dateTime); System.out.println("Formatted date: " + formattedDate); driver.quit(); }
关键修正点说明
- 获取日期值:替换
getText()为getAttribute("value"),Kendo UI的输入框会将选中的日期同步到value属性中,这才是正确的取值路径。 - 日期格式化:如果需要对日期进行规范格式化,先将字符串解析为
LocalDateTime对象,再用DateTimeFormatter进行格式化,避免错误调用String.format()。 - 资源清理:添加
driver.quit()确保浏览器正常关闭,避免资源泄漏。
内容的提问来源于stack exchange,提问作者Azory Kavhuru
相关产品推荐
相关产品推荐

