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

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

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

Unable to locate any date from return date calendar in Make My Trip website through selenium and Java

Here i am trying to select return date 12 of April month. i tried with different customized xpath and css but unable to locate the element:
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Make_my_trip {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "F:\\Selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.makemytrip.com/");
// Selecting Return date
driver.findElement(By.id("hp-widget__return")).click();
//WebDriverWait ws = new WebDriverWait(driver, 10);
//ws.until(ExpectedConditions.presenceOfElementLocated(By.id("dp1551508380301")));
Thread.sleep(2000);;
while (!driver.findElement(By.xpath("//span[#class ='ui-datepicker-month']")).getText().contains("April")) {
System.out.println("Return date selected ");
driver.findElement(By.xpath(
"div[#id='dp1551508898872']//span[#class='ui-icon ui-icon-circle-triangle-e'][contains(text(),'Next')"))
.click();
}
List<WebElement> returndate = driver.findElements(By.xpath("//a[#class ='ui-state-default']"));
int count = returndate.size();
for (int j = 0; j < count; j++) {
String returndatetext = driver.findElements(By.xpath("//a[#class ='ui-state-default']")).get(i).getText();
if (returndatetext.equalsIgnoreCase("12")) {
driver.findElements(By.xpath("//a[#class ='ui-state-default']")).get(i).click();
break;
}
}
}
PS :
If we use explicitly wait getting "org.openqa.selenium.InvalidSelectorException" Error so as of now use Thread.sleep(1000).
If we use Xpath //div[#class='ui-datepicker-group ui-datepicker-group-last']/div/a/span[contains(text(),'Next' )][1] getting
org.openqa.selenium.ElementNotVisibleException: element not visible
"Element not visible". I had this error too. It's mean your searchable element isn't visible in the current snapshot. You should focus on that element or scroll down till element appear in the snapshot

Selenium Webdrier using Java: Exception while reading from Excel

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

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+"]");

Element not found error while selecting dropdown in Java selenium

Here is the code i have written
I get the below error when the weblist selects second user from drop down the Error is
Caused by Element not found in the cache - perhaps the page has changed since it was looked up
The code is
import java.util.List;
import java.util.concurrent.TimeUnit;
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 SimpleBrowseroperation
{
public static void main(String[] args) throws InterruptedException
{
WebDriver driver = new FirefoxDriver();
//WebDriver driver = new InternetExplorerDriver();
//WebDriver driver = new ChromeDriver();
//driver.navigate().to("https://google.co.in");
driver.navigate().to("https://testnwadmin.aditi.com/nwadmin/spages/home.aspx");
List<WebElement> ele = driver.findElements(By.xpath("//*[#id='divLoginSection']/div/div[3]"));
driver.findElement(By.id("Login1_txtEmailID")).sendKeys("testdata5#aditi.com");
//driver.findElement(By.id("Login1_txtPassword")).sendKeys("Testing1*");
driver.findElement(By.id("Login1_btnLogin")).click();
driver.findElement(By.xpath("//*[#id='sliding-navigation']/li[2]/a")).click();
String ViewMorelink="//*[#id='divContentHolder']/div[2]/table[%s]/tbody/tr[3]/td";
String ClkViewMore="//*[#id='divContentHolder']/div[2]/table[%s]/tbody/tr[3]//a[contains(text(),'View')]";
String Covered="//*[#id='divContentHolder']/div[2]/table[%s]/tbody/tr[2]/td/table/tbody/tr[%s]/td[2]";
String ViewDetails="//*[#id='divContentHolder']/div[2]/table[%s]/tbody/tr[2]/td/table/tbody/tr[%s]/td[3]/a";
String TableRowCount="//*[#id='divContentHolder']/div[2]/table[%s]/tbody/tr[2]/td/table/tbody/tr";
String ViewCarrier="//*[#id='divContentHolder']/div[2]/table[%s]/tbody/tr[2]/td/table/tbody/tr[%s]/td[3]";
String ClaimPayer="//*[#id='divContentHolder']/div[2]/table[%s]/tbody/tr[2]/td/table/tbody/tr[%s]/td[4]";
Select WebList=new Select(driver.findElement(By.xpath("//*[#id='ddlSelectUser']")));
List<WebElement> userlist = WebList.getOptions();
int usercnt=userlist.size();
System.out.println(usercnt);
String[] linkTexts = new String[usercnt];
int i = 0;
for (WebElement e : userlist)
{
linkTexts[i] = e.getText();
i++;
}
for(int usrcnt=0;usrcnt<=usercnt;usrcnt++)
{
WebList.selectByIndex(usrcnt);
> /
> somecode
> /
}
}
}

Categories