gpt4 book ai didi

Java Selenium 使用 Apache POI - 读取 Excel 文件并将两行拉到一起

转载 作者:行者123 更新时间:2023-12-01 21:14:29 26 4
gpt4 key购买 nike

我使用以下代码 ( Reference link ) 从 Excel 文件中读取数据,并使用两个单元格中的数据来搜索 Google 网站。然而,当程序运行时,两行的数据一起放置在搜索框中,而不是像我期望的那样通过使用 For 循环在单独的迭代中一个接一个地放置。期待帮助。这是代码:

package readdatafile;

import java.io.*;
import java.util.concurrent.TimeUnit;

import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
// import org.openqa.selenium.firefox.FirefoxDriver;

public class DataDrivenUsingExcelFile {

String reafilefrom = "I:\\2000 QA\\Testing Tools\\Selenium\\Examples\\TestData\\testdata.xlsx";
public static void main(String[] args) throws IOException {

DataDrivenUsingExcelFile obj1 = new DataDrivenUsingExcelFile();

System.setProperty("webdriver.chrome.driver", "C://ChromeDriverForSelenium/chromedriver.exe");
WebDriver driver = new ChromeDriver();

driver.get("https://www.google.com");

driver.manage().window().maximize();

WebElement searchBox = driver.findElement(By.name("q"));

try{

FileInputStream file = new FileInputStream(new File(obj1.reafilefrom));
XSSFWorkbook workbook = new XSSFWorkbook(file);

XSSFSheet sheet = workbook.getSheetAt(0);

for (int i=1; i<= sheet.getLastRowNum(); i++){

String keyword = sheet.getRow(i).getCell(0).getStringCellValue();

searchBox.sendKeys(keyword);

searchBox.submit();

driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
}

workbook.close();
file.close();
} catch (FileNotFoundException fnfe){
fnfe.printStackTrace();
}

// Waiting a little bit
try {
Thread.sleep(5000);
} catch (InterruptedException e) {

e.printStackTrace();
}
driver.close();
driver.quit();
}

}

测试数据截图如下: enter image description here

谢谢。

最佳答案

对于 for 循环中的每次迭代,您需要在输入新的搜索字符串之前清除搜索文本输入字段。尝试下面的代码

for (int i=1; i<= sheet.getLastRowNum(); i++){
String keyword = sheet.getRow(i).getCell(0).getStringCellValue();
searchBox.clear();
searchBox.sendKeys(keyword);
searchBox.submit();
driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
}

关于Java Selenium 使用 Apache POI - 读取 Excel 文件并将两行拉到一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40515751/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com