
本文详解如何在 selenium webdriver 中读取双列 csv 文件,并将每行的两列数据分别填入网页两个不同输入框,配合固定操作完成批量表单提交。
在自动化测试或批量数据录入场景中,常需将外部结构化数据(如 CSV)映射到网页表单字段。当 CSV 包含两列(例如:用户名、邮箱),而目标页面有两个对应输入框(Element1 和 Element2),关键在于按行解构数组、按索引精准赋值,而非嵌套遍历。
以下为推荐实现方案(已整合异常处理与资源管理):
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
// 假设 driver 已初始化(如 ChromeDriver)
WebDriver driver = ...;
ArrayList<String[]> records = new ArrayList<>();
try (Scanner scan = new Scanner(new File("data.csv"))) {
while (scan.hasNextLine()) {
String[] line = scan.nextLine().trim().split(",", -1); // -1 保留空字段
if (line.length >= 2) { // 防止数据不全导致 ArrayIndexOutOfBoundsException
records.add(line);
}
}
} catch (FileNotFoundException e) {
throw new RuntimeException("CSV 文件未找到: data.csv", e);
}
// 逐行处理:record[0] → Element1, record[1] → Element2
for (String[] record : records) {
try {
// 清空并填入第一列数据到第一个输入框
driver.findElement(By.id("Element1")).clear();
driver.findElement(By.id("Element1")).sendKeys(record[0].trim());
// 清空并填入第二列数据到第二个输入框
driver.findElement(By.id("Element2")).clear();
driver.findElement(By.id("Element2")).sendKeys(record[1].trim());
// 执行固定操作:点击按钮
driver.findElement(By.id("Element3")).click();
driver.findElement(By.id("Element4")).click();
// 可选:添加显式等待,确保页面响应(如跳转/加载)
// new WebDriverWait(driver, Duration.ofSeconds(3)).until(...);
} catch (Exception e) {
System.err.println("处理行 [" + String.join(",", record) + "] 时出错: " + e.getMessage());
// 建议记录失败日志或截图,便于调试
continue; // 继续下一行,避免单行失败中断整个流程
}
}关键要点说明:
- ✅ 取消内层循环:原代码中 for (String temp1 : temp) 会将同一行的两列数据都塞进 Element1,导致逻辑错误;正确做法是直接通过 record[0] 和 record[1] 按列索引访问。
- ✅ 健壮性增强:使用 try-with-resources 自动关闭 Scanner;split(",", -1) 避免末尾空字段被忽略;if (line.length >= 2) 防止数据缺失异常。
- ✅ 用户体验优化:对输入框调用 .clear() 再 .sendKeys(),避免残留内容;.trim() 去除 CSV 中常见的首尾空格。
- ⚠️ 生产环境建议:
- 使用 Apache Commons CSV 或 OpenCSV 库替代手动 split(),支持引号包裹、换行符等复杂 CSV 格式;
- 将定位器(By.id(...))提取为 WebElement 常量或 Page Object 模式,提升可维护性;
- 添加失败重试机制或断言验证提交结果,确保流程可靠性。
该模式可轻松扩展至多列场景(如 record[2], record[3]),是 Selenium 数据驱动测试(DDT)的基础实践范式。
立即学习“Java免费学习笔记(深入)”;



















