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:
我使用以下代码(参考链接)从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();
}
}
Test data screenshot is below:
测试数据截图如下:
Thank you.
1 个解决方案
#1
3
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循环中的每次迭代,您需要在输入新的搜索字符串之前清除searchtext输入字段。请尝试以下代码
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);
}
#1
3
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循环中的每次迭代,您需要在输入新的搜索字符串之前清除searchtext输入字段。请尝试以下代码
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);
}