Maven项目中用Selenium+TestNG点击HTML日期选择器今日按钮
解决方案
核心原因
HTML5原生<input type="date">弹出的日历控件是浏览器自带的原生组件,不属于网页DOM结构,因此Selenium无法直接定位到「今天」这类按钮元素。
两种可行实现方式
方式1:通过JavaScript直接设置今日日期
直接修改输入框的value属性,效果和点击「今天」按钮完全一致,且兼容性最好:
package org.example; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.Test; import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class AppTest { public static WebDriver driver; @Test public void selectToday() throws InterruptedException { WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://www.wufoo.com/html5/date-type/"); // 等待元素加载(建议后续替换为显式等待) Thread.sleep(500); WebElement dateInput = driver.findElement(By.xpath("//*[@id='main']/section[1]/div/p[3]/input")); // 生成符合HTML5 date格式的今日日期字符串(yyyy-MM-dd) String todayDate = LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE); // 通过JS设置输入框值 ((JavascriptExecutor) driver).executeScript("arguments[0].value = arguments[1];", dateInput, todayDate); driver.quit(); } }
方式2:模拟键盘快捷键(仅部分浏览器支持)
Chrome等浏览器支持在日历弹出后按T键快速选择今日,可尝试此方式:
package org.example; import io.github.bonigarcia.wdm.WebDriverManager; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.Test; public class AppTest { public static WebDriver driver; @Test public void selectTodayViaKeyboard() throws InterruptedException { WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://www.wufoo.com/html5/date-type/"); Thread.sleep(500); WebElement dateInput = driver.findElement(By.xpath("//*[@id='main']/section[1]/div/p[3]/input")); // 点击输入框弹出日历 dateInput.click(); // 按T键选择今日(仅Chrome等部分浏览器支持) dateInput.sendKeys(Keys.T); driver.quit(); } }
额外优化建议
- 统一Selenium版本:你的pom.xml中
selenium-java(3.141.59)和selenium-firefox-driver(4.1.1)版本不一致,建议统一升级到最新稳定版,避免版本冲突。 - 替换
Thread.sleep():改用Selenium的显式等待(WebDriverWait)提升代码稳定性,示例:
import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; import java.time.Duration; // ... WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement dateInput = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='main']/section[1]/div/p[3]/input"))); // ...
内容的提问来源于stack exchange,提问作者Fahim
相关产品推荐
相关产品推荐

