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

如何在Selenium Webdriver中获取表格行内的日历控件值?

Selenium读取表格内嵌日历控件值的解决方案

问题原因

WebElement.getText() 仅能读取DOM元素的可见文本内容,而日历控件属于<input>类型的表单元素,选中的日期值存储在元素的value属性中,不属于文本节点范畴,因此直接调用getText()会返回空值,无法正常读取。
同时你提供的原始代码存在多处变量名拼写错误,也会导致运行异常。

修正后的实现代码

// 表格行定位路径
String searchResultXpath = "//*[@id='accountTable']/table/tbody/tr";
List<WebElement> searchResult = driver.findElements(By.xpath(searchResultXpath));
int resultSize = searchResult.size();

for (int i = 0; i < resultSize; i++) {
    WebElement currentRow = searchResult.get(i);
    // 单独处理第一行首个单元格的日历控件
    if (i == 0) {
        List<WebElement> firstRowCells = currentRow.findElements(By.xpath("./td"));
        if (!firstRowCells.isEmpty()) {
            // 定位日历控件的input节点,读取value属性
            WebElement calendarInput = firstRowCells.get(0).findElement(By.xpath(".//input"));
            String calendarDate = calendarInput.getAttribute("value");
            System.out.print(calendarDate + "\t");
            // 读取第一行剩余单元格内容
            for (int j = 1; j < firstRowCells.size(); j++) {
                System.out.print(firstRowCells.get(j).getText() + "\t");
            }
            System.out.println();
            continue;
        }
    }
    // 其余行直接读取整行文本
    System.out.println(currentRow.getText());
}

补充说明

如果日历控件的value属性返回的是时间戳或非格式化的原始值,你可以根据业务需求对读取到的calendarDate做日期格式化处理后再输出即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 22:45:05