Hi,
Can any one help me to create a selenium script for the below testing requirement.
1. Open chrome and navigate to google .com
2. Read the search strings(selenium,UFT,Loadrunner) from excel spread sheet and perform search.
3.Capture the serach results for each string and write into the same excel against the search string( for example- Selenium(column1) and serach results(About 50,400,000 results (0.61 seconds) ) in next column
I created the below code but it is working only for 1 row of data:
Code:
System.setProperty("webdriver.chrome.driver", "c:\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.google.com");
WebElement element = driver.findElement(By.name("q"));
FileInputStream file = null;
try {
file = new FileInputStream(ExcelPath);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
try {
book = WorkbookFactory.create(file);
} catch (IOException e) {
e.printStackTrace();
}
sheet = book.getSheet(sheetname);
Object data[][] = new Object[sheet.getLastRowNum()][sheet.getRow(0).getLastCellNum()];
for(int i=0; i<sheet.getLastRowNum(); i++){
for(int k=0; k<sheet.getRow(0).getLastCellNum(); k++){
data[i][k] = sheet.getRow(i).getCell(k).toString();
element.sendKeys(data[i][k].toString());
element.submit();
String searchResults = driver.findElement(By.xpath("//div[@id='resultStats']")).getText();
Thread.sleep(4000);
int col=k+1;
ExcelUtil.writeexcel(ExcelPath,sheetname,searchResults, i,col);
Thread.sleep(2000);
driver.navigate().back();
Thread.sleep(3000);
element.sendKeys(data[i+1][k].toString());
element.submit();
}
public static void writeexcel(String ExcelPath, String SheetName,String text , int rowno , int colno) {
try {
File f= new File(ExcelPath);
if(!f.exists()){
System.out.println("File not Found so new file created");
Workbook wb = new XSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream(ExcelPath);
wb.createSheet(SheetName);
wb.write(fileOut);
wb.close();
fileOut.close();
}
System.out.println("File Found so updating the existing file");
fis = new FileInputStream(ExcelPath);
wb = WorkbookFactory.create(fis);
// sh = wb.createSheet(SheetName);
sh = wb.getSheet(SheetName);
if(sh == null){
sh = wb.getSheet(SheetName);
}
}catch(Exception e)
{System.out.println(e.getMessage());
}
try{
row = sh.getRow(rowno);
if(row == null){
row = sh.createRow(rowno);
}
cell = row.getCell(colno);
if(cell!=null){
cell.setCellValue(text);
}
else{
cell = row.createCell(colno);
cell.setCellValue(text);
}
fos = new FileOutputStream(ExcelPath);
wb.write(fos);
fos.flush();
fos.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
Thanks
Sun