使用Apache POI的Java Selenium – 读取一个Excel文件将这两个行拉在一起

我已经使用下面的代码( 参考链接 )从Excel文件中读取数据,并使用两个单元格中的数据来searchGoogle网站。 但是,程序运行时,两行数据放在search框中,而不是在单独的迭代中一个接一个,因为我期望通过使用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(); } } 

testing数据截图如下: 在这里输入图像说明

谢谢。

对于for循环中的每个迭代,您需要在input新的searchstring之前清除search文本input字段。 尝试下面的代码

 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); }