




本文详解如何在 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 = ...; ArrayListrecords = 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; // 继续下一行,避免单行失败中断整个流程 } }
关键要点说明:

该模式可轻松扩展至多列场景(如 record[2], record[3]),是 Selenium 数据驱动测试(DDT)的基础实践范式。