如何读取Map列表并通过Selenium依次向UI填充数据
遍历Map列表实现Selenium UI数据填充(TestNG场景)
你可以通过遍历List<Map<String,String>>中的每一个Map对象,逐个提取键值对来填充对应UI元素,完成一行数据填充后点击保存,循环处理所有行数据。以下是完整的实现代码及关键说明:
完整代码示例
import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.Select; import org.testng.annotations.Then; import java.util.List; import java.util.Map; @Then("User Enters Data") public void feedData(IDataReader dataTable) { // 获取所有行的数据列表 List<Map<String,String>> dataList = dataTable.getAllRows(); // 循环处理每一行数据 for(Map<String, String> rowData : dataList) { // 1. 填充文本框:替换为你项目中实际的元素定位器 WebElement textBox = driver.findElement(By.id("text_box_locator")); textBox.clear(); // 清空原有内容 textBox.sendKeys(rowData.get("TextBox")); // 2. 处理下拉框:根据实际需求选择定位器和选择方式 Select dropDown = new Select(driver.findElement(By.xpath("//select[@name='dropdown']"))); dropDown.selectByVisibleText(rowData.get("DropDown")); // 若需通过value值选择,可替换为:dropDown.selectByValue(rowData.get("DropDown")); // 3. 填充描述框 WebElement descriptionBox = driver.findElement(By.cssSelector("textarea#description")); descriptionBox.clear(); descriptionBox.sendKeys(rowData.get("Description")); // 4. 点击保存按钮 WebElement saveButton = driver.findElement(By.id("save_btn")); saveButton.click(); // 可选:保存后如果页面刷新/跳转,添加等待确保表单重新加载完成 // WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); // wait.until(ExpectedConditions.visibilityOf(textBox)); } }
关键说明
- 遍历数据列表:使用增强for循环遍历
dataList,每个rowData对应一行完整的表单数据 - 提取Map中的值:通过
rowData.get("键名")获取对应数据,键名必须和你数据中的键严格匹配(比如"TextBox"、"DropDown") - 元素定位:将代码中的定位器(
By.id/By.xpath等)替换为你项目中实际的UI元素定位方式 - 输入框处理:每次填充前调用
clear()清空输入框,避免原有内容干扰新数据 - 下拉框处理:根据下拉框的实际实现,选择
selectByVisibleText或selectByValue方法 - 等待逻辑:如果保存操作导致页面跳转或刷新,必须添加显式等待,确保下一次填充前表单元素已加载完成
内容的提问来源于stack exchange,提问作者Pet
相关产品推荐
相关产品推荐

