Selenium Webdrier using Java: Exception while reading from Excel - java

I am using SeleniumWebDriver using Java to automation one of the portal applications. As part of this, I want to read username and password from Excel and written below code. But seeing Exception in thread "main" java.lang.NoClassDefFoundError: org/openxmlformats/schemas/drawingml/x2006/main/ThemeDocument Below is the code
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.util.Random;
public class BankingFaceLift {
static WebDriver driver = null;
public static void main(String[]args){
driver = new FirefoxDriver();
driver.get("https://obsit.enbduat.com/obweb/common/login.jsf?faces-redirect=true");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
try
{
File file = new File("TestData.xlsx");
FileInputStream iFile = new FileInputStream(file);
XSSFWorkbook wb = new XSSFWorkbook(iFile);
XSSFSheet sheet = wb.getSheet("Sheet1");
int rowCount = sheet.getLastRowNum();
System.out.println("the no of rows are : " + rowCount);
for (int row=1; row<=rowCount; row++)
{
String Username = sheet.getRow(row).getCell(0).getStringCellValue();
String Password = sheet.getRow(row).getCell(1).getStringCellValue();
driver.findElement(By.id("username")).sendKeys(Username);
driver.findElement(By.id("j_idt49")).sendKeys(Password);
driver.findElement(By.id("submit")).click();
I have imported poi-xxx.jar and poi-ooxml.jar1.
Kindly advice Thanks!

You need to import poi-ooxml-schemas jar as well. You can download the jar from here

Related

Linkedin login screen Java Selenium can't sign out

I created an excel with random emails and passwords in 2 coulmns and excel name is "deneme5". Selenium automatically tries all the emails but once it's logged in with the correct one it's not logging out. Plus it doesn't write the info if the test passed or failed to the excel file.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
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.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Excel_Read_Write {
WebDriver driver;
WebDriverWait wait;
XSSFWorkbook workbook;
XSSFSheet sheet;
XSSFCell cell;
public void ReadData() throws IOException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Lenovo\\Desktop\\chromedriver.exe"); //location of cromdriver exe
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15));
driver.get("https://www.linkedin.com/login/tr");
driver.manage().window().maximize();
//new WebDriverWait(driver, Duration.ofSeconds(30));
File src= new File("C:\\Users\\Lenovo\\Desktop\\deneme5.xlsx"); //excel sheet which i put 10 random email and password which one of them is true
FileInputStream finput = new FileInputStream(src);
workbook = new XSSFWorkbook(finput);
sheet= workbook.getSheetAt(0);
for(int i=1; i<= sheet.getLastRowNum() ; i++) {
XSSFCell cell3 =sheet.getRow(i).createCell(3);
//this loop for writing all the email and passwords one by one
System.out.print("Sena");
cell = sheet.getRow(i).getCell(0);
cell .setCellType(CellType.STRING);
driver.findElement(By.id("username")).sendKeys(cell.getStringCellValue());
cell = sheet.getRow(i).getCell(1);
cell.setCellType(CellType.STRING);
driver.findElement(By.id("password")).sendKeys(cell.getStringCellValue());
driver.findElement(By.className("btn__primary--large")).click();
driver.findElement(By.id("username")).clear();
String actualUrl="https://www.linkedin.com/feed/";
String expectedUrl= driver.getCurrentUrl();
if(actualUrl.equalsIgnoreCase(expectedUrl)) {
//driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15));
cell3.setCellType(CellType.STRING);
cell3.setCellValue("test passed");
driver.findElement(By.id("ember19")).click();
driver.findElement(By.linkText("Sign Out")).click();
}
else { cell3.setCellValue("test failed");
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15));
driver.findElement(By.id("username")).clear();
}}
FileOutputStream outputStream = new FileOutputStream("C:\\Users\\Lenovo\\Desktop\\deneme5.xlsx");
workbook.write(outputStream);
workbook.close();
}}
Add the Thread Sleep after launching browser.
Also replace last two lines of your code with below lines.
driver.findElement(By.xPath("//button[contains(#id, 'ember')]")).click();
Thread.Sleep(3000);
driver.findElement(By.linkText("Sign Out")).click();

java.lang.IllegalArgumentException: Sheet index (26) is out of range (0..2)

When i am trying to write data into excel sheet, i am getting above Exception. Please refer the solution for my problem.
Please find my code below:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.poi.ss.usermodel.Row;
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;
import org.openqa.selenium.support.ui.Select;
public class CityBusRoutes {
static String routeName;
static String routeList;
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.chrome.driver",
"D://Selenium//Selenium Drivers//chromedriver_win32//chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.onefivenine.com/busRoute.dont?method=findBusRoute");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
Select ddl1 = new Select(driver.findElement(By.id("cityId")));
List<WebElement> elementCount = ddl1.getOptions();
int citiesCount = elementCount.size();
for (int i = 1; i <= citiesCount; i++) {
ddl1.selectByIndex(i);
Select ddl2 = new Select(driver.findElement(By.id("routeId")));
List<WebElement> element = ddl2.getOptions();
int routesCount = element.size();
for (int j = 1; j <= routesCount; j++) {
ddl2.selectByIndex(j);
routeName = driver.findElement(By.xpath("html/body/table/tbody/tr[3]/td[2]/div[2]/table[2]")).getText();
routeList = driver
.findElement(By.xpath("html/body/table/tbody/tr[3]/td[2]/div[2]/table[3]/tbody/tr/td[1]"))
.getText();
FileInputStream input = new FileInputStream("D:\\Citybus-Routes-List.xlsx");
XSSFWorkbook wBook = new XSSFWorkbook(input);
XSSFSheet sh = wBook.getSheetAt(citiesCount);
int rowCount = sh.getLastRowNum() - sh.getFirstRowNum();
Row newRow = sh.createRow(rowCount + 1);
newRow.createCell(0).setCellValue(routeName);
newRow.createCell(1).setCellValue(routeList);
input.close();
FileOutputStream output = new FileOutputStream("D:\\Citybus-Routes-List.xlsx");
wBook.write(output);
wBook.close();
output.close();
}
driver.quit();
}
}
}
Below is my StackTrace:
Exception in thread "main" java.lang.IllegalArgumentException: Sheet index (26) is out of range (0..3)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.validateSheetIndex(XSSFWorkbook.java:1236)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.getSheetAt(XSSFWorkbook.java:991)
at CityBusRoutes.main(CityBusRoutes.java:86)
After completion of one j loop iteration, showing below error:
Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
(Session info: chrome=60.0.3112.90)
(Driver info: chromedriver=2.29.461591 (62ebf098771772160f391d75e589dc567915b233),platform=Windows NT 6.1.7600 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 30 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
The problem is that you are trying to get sheet that has not been created.
Try to replace
XSSFSheet sh = wBook.getSheetAt(citiesCount);
with
XSSFSheet sh = wBook.createSheet(String.valueOf(i)); //change sheet name if needed

Eclipse - Data Driven Framework - Error Shown

I have written a data driven framework Java program using below 2 classes. Inthis prgram am trying to log into system by taking login ids from external excel file.
DDF_ExcelClass - library java class to take data from external excel
file and will be called in SnapDealLogin_2
SnapDealLogin_2 - datadrivenframework java program which is failed. In
this class am taking login data from external excel file using
DDF_ExcelClass.
The error message shown are java.lang.RuntimeException: and
java.lang.ArrayIndexOutOfBoundsException: 5
Please note if login ids are given inside the program (not taking from external excel file) then SnapDealLogin_2 works good. failing when try to
take login ids from excel file.
I have tried to identify the cause of fail but could not. please help.
// Data Driver Framework - Excel Class stored as Library to reuse
package datadrivenframework;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import java.io.File;
import java.io.FileInputStream;
public class DDF_ExcelClass{
XSSFWorkbook Snap_WB;
XSSFSheet Snap_Sheet;
// NAVIGATING TO THE EXCEL FILE
public DDF_ExcelClass(String Path) throws Exception{
File Snap_Excel = new File(Path);
FileInputStream Snap_Input = new FileInputStream(Snap_Excel);
Snap_WB = new XSSFWorkbook(Snap_Input);
Snap_WB.close();
}
// NAVIGATING TO THE EXCEL SHEET AND GETTING THE CELL VALUE THEN RETURNING THE SAME
public String Snap_ok(int SheetIndex, int Row, int Column){
Snap_Sheet = Snap_WB.getSheetAt(SheetIndex);
String Snap_DataR = Snap_Sheet.getRow(Row).getCell(Column).getStringCellValue();
//System.out.println("THE VALUE IN THE ROW " + Row + " IS " + Snap_DataR);
return Snap_DataR;
}
// FINDING THE TOTAL ROW COUNT IN THE DATA SHEET AND RETURNING THE SAME
public int filerowcount(int SheetID){
int rowcount = Snap_WB.getSheetAt(SheetID).getLastRowNum();
//rowcount = rowcount+1;
return rowcount;
}
}
This is a simple data driver framework program where data is taken from external excel file
package datadrivenframework;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
import datadrivenframework.DDF_ExcelClass;
public class SnapDealLogin_2 {
#Test(dataProvider = "ABN") // declaring that # Test annotation should get value from dataProvider annotation named "ABN" to proceed further
public void Snap_Login(String UserID) throws InterruptedException{
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\hp\\workspace\\Selenium\\browser\\chromedriver.exe"); // declaring the location of Chromedriver
WebDriver Snap = new ChromeDriver(); // initializing webdriver Snap as ChromeDriver
Snap.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // adding implicit wait
Snap.get("https://www.snapdeal.com/");// entering snapdeal web url
Thread.sleep(3000);// adding sleep
Snap.manage().window().maximize(); // maximizing the browser
Thread.sleep(2000);// adding sleep
Snap.findElement(By.xpath(".//*[#id='sdHeader']/div[4]/div[2]/div/div[3]/div[3]/div/span[1]")).click();// clicking Sign-On button
Snap.findElement(By.xpath("//a [#href='https://www.snapdeal.com/login']")).click(); // Clicking Login button
Snap.switchTo().frame("loginIframe"); // Switching the webdriver control to new frame "Loginframe"
Snap.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);// adding implicit wait
Snap.findElement(By.id("userName")).sendKeys(UserID); // entering User id
Snap.findElement(By.id("checkUser")).click(); //clicking "Continue"button
Snap.quit(); // closing the window
}
#DataProvider(name = "ABN") // adding annotation as DataProvider and naming it as "ABN"
public Object [][] Snap_DP() throws Exception{
DDF_ExcelClass DEC = new DDF_ExcelClass("C:\\Users\\hp\\Desktop\\User_Credentials.xlsx");
int rowcount = DEC.filerowcount(0);
Object[][] xlobject = new Object[rowcount][1];
for(int I = 0; I<=rowcount; I++){
xlobject[I][0] = DEC.Snap_ok(0, I, 0);
}
return xlobject;
}
}

Eclipse not showing run as java application, only showing run configurations

This is my code.
Still building it.
But just wanted to check if the syso works.
package mySeleniumProjects;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ReadExcelExample {
static WebDriver driver = new FirefoxDriver();
static String username;
static String passwd;
static String baseURL = "http://www.guru99.com";
int rowNum;
int colNum;
public void main (String[] args) throws IOException{
File excel = new File("Gave File path here");
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet ws = wb.getSheet("Sheet1");
rowNum = ws.getLastRowNum();
colNum = ws.getRow(0).getLastCellNum();
System.out.println(rowNum);
System.out.println(colNum);
}
}
When I try to run it the only option I am getting is "Run Configurations".
Why I am not getting run as java application option?
I don't know how to choose run time configuration.
Can somebody help?
Method signature is incorrect:
You mentioned:
public void main (String[] args) throws IOException
It should be:
public static void main (String[] args) throws IOException
Write click on your java file. then on the next window search for 'java application', then click on 'New launch configuration' and select your java file and click on run. It will run your java program successfully.

Invalid selector error when trying to export webtable to excel

Error is:
The given selector table[class='stats_table data_grid'] tbody tr [0] td [0] is either invalid or does not result in a WebElement. The following error occurred:
InvalidSelectorError: An invalid or illegal selector was specified
Observation:
I have checked the cssSelector without ["+r+"] and ["+c+"] and it is valid.
So the error is coming from adding ["+r+"] and ["+c+"], and I am unable to mitigate it. My overall goal is to take data from webtable from mlb.com/stats and
enter it into an excel sheet. Almost 99 percent of the code is working fine,
except for the invalid cssSelector issue.
My code is:
package automate;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
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.firefox.FirefoxDriver;
public class MLBtoXL {
static WebDriver driver = new FirefoxDriver();
public static void main(String[] args) throws IOException {
// Navigate to mlb.com/stats
driver.navigate().to("http://goo.gl/El1PIV");
WebElement table = driver.findElement(By.cssSelector
("table[class='stats_table data_grid']"));
List<WebElement> irow = table.findElements(By.tagName("tr"));
int iRowCount = irow.size();
List<WebElement> icol = table.findElements(By.tagName("td"));
int iColCount = icol.size();
FileOutputStream fos = new FileOutputStream
("/Users/HARSHENDU/Desktop/MLBtoXL.xlsx");
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet ws = wb.createSheet("Team Stats");
for(int r=0; r<=iRowCount; r++) {
XSSFRow excelrow = ws.createRow(r);
for(int c=0; c<iColCount; c++) {
// Invalid selector exception coming up for the following cssSelector.
WebElement cellval = driver.findElement
(By.cssSelector("table[class='stats_table data_grid'] tbody tr ["+r+"] td ["+c+"]"));
String cellcontent = cellval.getText();
XSSFCell excelcell = excelrow.createCell(c);
excelcell.setCellType(XSSFCell.CELL_TYPE_STRING);
excelcell.setCellValue(cellcontent);
}
System.out.println("");
}
fos.flush();
wb.write(fos);
fos.close();
end();
}
public static void end() {
driver.close();
driver.quit();
}
}
I believe using an XPath would solve your issue:
WebElement cellval = driver.findElement(By.XPath("//table[#class='stats_table data_grid']/tbody/tr["+r+"]/td["+c+"]"));
You need to add the index attribute. Try
WebElement cellval = driver.findElement(By.cssSelector("table[class='stats_table data_grid'] tbody tr[index="+r+"] td[index="+c+"]");

Categories