Java Selenium使用Apache POI读取Excel文件,将两行放在一起
我使用以下代码(Reference link)从Excel文件中读取数据,并使用两个单元格中的数据搜索谷歌网站。然而,当程序运行时,来自两行的数据一起放在搜索框中,而不是像我预期的那样,在单独的迭代中一个接一个地使用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();
}
}
谢谢
# 1 楼答案
对于For循环中的每个迭代,在输入新的搜索字符串之前,需要清除searchtext输入字段。试试下面的代码