Reputation: 676
I have used the following code (Reference link) to read data from an Excel file and using the data in two cells to search the Google site. However, when the program is run, data from two rows are placed in the searchbox together, not one after another in separate iteration as I'm expecting it by using the For loop. Looking forward to help. Here is the code:
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();
}
}
Test data screenshot is below:
Thank you.
Upvotes: 0
Views: 556
Reputation: 4832
For every iteration in the for loop, you need to clear the searchtext input field before entering the new search string. Try the below code
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);
}
Upvotes: 3