How do I extract lists to excel? - apache

I apologize if this is a stupid question.But why can I only extract one list to an excel? I've tried modifying it but I don't really understand why I can't have 2 columns side by side with the extracted data. Instead it displays one.
Any fixes?
I have following code :
public class dads
{
public static void main(String args[]) throws Exception
{
SXSSFWorkbook workbook = new SXSSFWorkbook(100);
SXSSFSheet sheet = workbook.createSheet("output");
FileOutputStream f = new FileOutputStream("czPA LEASE.xlsx",true);
// DRIVER
WebDriver driver=new FirefoxDriver();
driver.get("https://en.wikipedia.org/wiki/List_of_Death_Note_episodes");
List<WebElement> Elements=driver.findElements(By.xpath("//table//tbody//td//i"));
int x=-1;
int y=1;
for(WebElement ele: Elements)
{
System.out.println(ele.getText());
SXSSFRow dataRow = sheet.createRow((short)++x);
SXSSFCell cell=dataRow.createCell(0);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(ele.getText());
}
List<WebElement> Elements1=driver.findElements(By.xpath("//table//tbody//td"));
int x1=-1;
int y1=2;
for(WebElement ele1: Elements1)
{
System.out.println(ele1.getText());
SXSSFRow dataRow = sheet.createRow((short)++x1);
SXSSFCell cell1=dataRow.createCell(1);
cell1.setCellType(HSSFCell.CELL_TYPE_STRING);
cell1.setCellValue(ele1.getText());
}
try
{
f.flush();
workbook.write(f);
f.close();
System.out.println("Excel written successfully..");
driver.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

I hope this will help you to find you answer:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class Test {
static WebDriver driver = new FirefoxDriver();
static WebElement element ;
public static void main(String[] args) throws InterruptedException, IOException {
String excelFileName = "C:/Test.xls";//name of excel file
String sheetName = "Sheet1";//name of sheet
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(sheetName) ;
// DRIVER
WebDriver driver=new FirefoxDriver();
driver.get("https://en.wikipedia.org/wiki/List_of_Death_Note_episodes");
List<WebElement> rows=driver.findElements(By.xpath(".//table[#class='wikitable'][1]//th[contains(#id,'ep')]"));
//iterating r number of rows
for (int r=0;r < rows.size(); r++ )
{
HSSFRow row = sheet.createRow(r);
List<WebElement> cloumns = driver.findElements(By.xpath(".//table[#class='wikitable'][1]//th[#id='ep"+r+"']//parent::tr[1]/td"));
//iterating c number of columns
for (int c=0;c < cloumns.size(); c++ )
{
HSSFCell cell = row.createCell(c);
cell.setCellValue(cloumns.get(c).getText());
}
}
FileOutputStream fileOut = new FileOutputStream(excelFileName);
//write this workbook to an Outputstream.
wb.write(fileOut);
fileOut.flush();
fileOut.close();
}
}

Related

Receiving null point exception in the console for method even after having parameters in the method

Getting error at this method
gettablevalueshopcart("//div[#id='Catalog']//tr",2,"Large Angelfish",0,"EST-1");
Browser launching
public class petstore {
public static WebDriver driver;
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\achelimi\\Downloads\\chromedriver_win32 (1)\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to("https://jpetstore.cfapps.io/catalog");
driver.findElement(By.xpath("//a[contains(text(),'Sign In')]")).click();
driver.findElement(By.name("username")).sendKeys("Testing15");
driver.findElement(By.name("password")).sendKeys("test#123");
driver.findElement(By.id("login")).click();
driver.findElement(By.xpath("//div[#id='SidebarContent']/a[contains(#href,'FISH')]/img")).click();
driver.findElement(By.xpath("//td[contains(text(),'Angelfish')]//preceding-sibling::td//a")).click();
gettablevalueshopcart("//div[#id='Catalog']//tr",2,"Large Angelfish",0,"EST-1");
// gettablevalueshopcart("//div[#id='Catalog']//tr",2,"",0,"");
driver.quit();
}
created below method
public static void gettablevalueshopcart(String xPath1,int descriptionid, String expectvalue1, int itemid, String expectedvalue2) {
Used try and catch ,able to see output as null
try
{
//String xPath1 = "//div[#id='Catalog']//tr";
List<WebElement> shoppingtableList = driver.findElements(By.xpath(xPath1));
System.out.println("Item ID\t\tProduct ID\t\tDescription\t\tInstock\t\tList Price\tTotalcost\t\tButton");
System.out.println("---------------------------------------------------------------------------------------------------------------------------------");
for(int i=1;i<shoppingtableList.size();i++) {
List<WebElement> listData = driver.findElements(By.xpath(xPath1+"["+(i+1)+"]/td"));
for(int j=0;j<listData.size();j++) {
System.out.print(listData.get(j).getText()+"\t\t");
}
System.out.println();
}
// description is in the 3rd(2nd index) column so we can fetch that with the index number 2.
for(int i=1;i<shoppingtableList.size();i++) {
List<WebElement> listData = driver.findElements(By.xpath(xPath1+"["+(i+1)+"]/td"));
Compared expected output with actual value
if(listData.get(descriptionid).getText().trim().equals(expectvalue1))
{
System.out.println("Description for Item ID is "+listData.get(descriptionid).getText());
}
Compared expected output with actual value
if(listData.get(itemid).getText().trim().equals(expectedvalue2)) {
System.out.println("Item ID is "+listData.get(itemid).getText());
break;
}
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
This is the entire code.Copy and paste it.I have declared WebDriver globally.
package SeleniumPractice;
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.List;
import org.openqa.selenium.WebElement;
public class TestS_1 {
public static WebDriver driver;
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\achelimi\\Downloads\\chromedriver_win32 (1)\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to("https://jpetstore.cfapps.io/catalog");
driver.findElement(By.xpath("//a[contains(text(),'Sign In')]")).click();
driver.findElement(By.name("username")).sendKeys("Testing15");
driver.findElement(By.name("password")).sendKeys("test#123");
driver.findElement(By.id("login")).click();
driver.findElement(By.xpath("//div[#id='SidebarContent']/a[contains(#href,'FISH')]/img")).click();
driver.findElement(By.xpath("//td[contains(text(),'Angelfish')]//preceding-sibling::td//a")).click();
gettablevalueshopcart("//div[#id='Catalog']//tr",2,"Large Angelfish",0,"EST-1");
driver.quit();
}
public static void gettablevalueshopcart(String xPath1,int descriptionid, String expectvalue1, int itemid, String expectedvalue2)
{
try
{
//String xPath1 = "//div[#id='Catalog']//tr";
List<WebElement> shoppingtableList = driver.findElements(By.xpath(xPath1));
System.out.println("Item ID\t\tProduct ID\t\tDescription\t\tInstock\t\tList Price\tTotalcost\t\tButton");
System.out.println("---------------------------------------------------------------------------------------------------------------------------------");
for(int i=1;i<shoppingtableList.size();i++) {
List<WebElement> listData = driver.findElements(By.xpath(xPath1+"["+(i+1)+"]/td"));
for(int j=0;j<listData.size();j++) {
System.out.print(listData.get(j).getText()+"\t\t");
}
System.out.println();
}
// description is in the 3rd(2nd index) column so we can fetch that with the index number 2.
for(int i=1;i<shoppingtableList.size();i++) {
List<WebElement> listData = driver.findElements(By.xpath(xPath1+"["+(i+1)+"]/td"));
if((listData.get(descriptionid).getText()).trim().equals(expectvalue1))
{
System.out.println("Description for Item ID is "+listData.get(descriptionid).getText());
}
if(listData.get(itemid).getText().trim().equals(expectedvalue2)) {
System.out.println("Item ID is "+listData.get(itemid).getText());
break;
}
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Here is the output:
Item ID Product ID Description Instock List Price Totalcost Button
---------------------------------------------------------------------------------------------------------------------------------
EST-1 FI-SW-01 Large Angelfish $16.50 Add to Cart
EST-2 FI-SW-01 Small Angelfish $16.50 Add to Cart
Description for Item ID is Large Angelfish
Item ID is EST-1

Read Data from Excel is not working, not reading data to my application, I have shared my public repository.please have a look

I am trying to read Data from Excel file and input data to my web application but its not working.
Please have a look at my code.This is the class created for excel
I used Apache POI
Excel class
package ReadExcel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class Excel_Data {
HSSFWorkbook wb;
HSSFSheet sheet1;
public Excel_Data(String fileName,String sheetName) throws Exception {
File src= new File("E:\\Jino_testing\\Git_Hub\\Zmarta_se\\resources\\Zmarta.xls");
FileInputStream fis = new FileInputStream(src);
HSSFWorkbook wb = new HSSFWorkbook(fis);
}
public String getData( int sheetNumber, int row,int column) {
HSSFSheet sheet1 =wb.getSheetAt(0);
String data =sheet1.getRow(row).getCell(column).getStringCellValue();
return data;
}
}
This is my Test class which I am running
public void ApplyLoan() throws Exception {
//Reading Excel
Excel_Data read = new Excel_Data("Zmarta.xls","Co-Applicant" );
Thread.sleep(3000);
driver.findElement(apply).click();
driver.findElement(loan).click();
Thread.sleep(7000);
driver.findElement(amount).sendKeys(read.getData(0,1,1));
Thread.sleep(3000);
new Select (driver.findElement(years)).selectByVisibleText("14 år");
}
There are various errors in your code, here is the corrected code...
Here is your Excel_Data class
public class Excel_Data {
HSSFWorkbook wb;
HSSFSheet sheet1;
HSSFCell cell;
public Excel_Data(String fileName) throws Exception {
FileInputStream fis = new FileInputStream(fileName);
wb = new HSSFWorkbook(fis);
}
public String getData(int sheetNumber, int row, int column) {
sheet1 = wb.getSheetAt(sheetNumber);
String data = "";
try{
cell = sheet1.getRow(row).getCell(column);
switch(cell.getCellTypeEnum()) {
case BOOLEAN:
data = cell.getRawValue();
break;
case NUMERIC:
data = cell.getRawValue();
break;
case STRING:
data = cell.getStringCellValue();
break;
default:
break;
}
}catch(Exception e){
e.printStackTrace();
}
return data;
}
}
Here is Test class
public void ApplyLoan() throws Exception {
//Reading Excel
Excel_Data read = new Excel_Data("E:\\Jino_testing\\Git_Hub\\Zmarta_se\\resources\\Zmarta.xls");
Thread.sleep(3000);
driver.findElement(apply).click();
driver.findElement(loan).click();
Thread.sleep(7000);
driver.findElement(amount).sendKeys(read.getData(0,1,1));
Thread.sleep(3000);
new Select (driver.findElement(years)).selectByVisibleText("14 år");
}
Note -> HSSFWorkbook is to read from .xls file... use XSSFWorkbook to read from .xlsx file.

Getting first set of data as null value while using data provider in selenium

I am trying to fetch the data using data provider in selenium from an excel sheet. When the data is returned/passed on to the caller function, i get null values for the first time even though loop begins from the second row having the actual data. I am not sure why this is happening.
package pageobjectmodel;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import Utils.ReadingExcelfile;
import Utils.TestBase;
import pagebasedexecution.LinkedInloginPage;
public class LinkedInLoginTest extends TestBase
{
//public static ReadExcel excelfile;
public static ReadingExcelfile excelfile;
LinkedInloginPage loginPage;
public LinkedInLoginTest() throws IOException
{
super();
}
#BeforeMethod
public void Setup() throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
BrowserSetup();
loginPage = new LinkedInloginPage();
}
#Test(dataProvider="TestData")
public void LoginTest(String uname, String password) throws InterruptedException
{
// System.out.println("received data is --- " +uname + " , " + password);
loginPage.LoginIntoAccount(uname, password);
String title = loginPage.VerifyTitle();
Assert.assertEquals(title, "LinkedIn", "Unable to login: invalid credentials");
Thread.sleep(5000);
}
/*#Test(priority=2)
public void VerifyloginPageTitleTest() throws InterruptedException
{
String title = loginPage.VerifyTitle();
Assert.assertEquals(title, "LinkedIn", "Unable to login: invalid credentials");
}*/
#DataProvider
public Object[][] TestData() throws IOException
{
excelfile = new ReadingExcelfile(System.getProperty("user.dir")+"\\src\\main\\java\\testData\\LinkedIn.xlsx");
int rows = excelfile.RowCount(1);
int colm = excelfile.TotalColm("LoginPage", 0);
Object[][] credentials = new Object[rows][colm];
for(int i = 1; i < rows; i++)
{
for(int j = 0; j<colm; j++)
{
credentials[i][j] = excelfile.getdata("LoginPage", i, j);
System.out.println("Fetched data from excel sheet is -- "+credentials[i][j]);
}
}
return credentials;
}
#AfterMethod
public void closebrowser()
{
System.out.println("quitting browser");
driver.quit();
}
}
Even though i am fetching the data from second row, somehow it's fetching the data from first row(column names) and first set of data is returned as null, null. i have provided the screenshot of error console and highlighted the error portion. Any help is appreciated.
Thanks
This is because here
Object[][] credentials = new Object[rows][colm];
you are creating array of object with number of rows and colums present in your sheet but you are inserting value in this array from second row So In first row it is taking default null values.
Replace code :
for(int j = 0; j<colm; j++)
{
credentials[i][j] = excelfile.getdata("LoginPage", i, j);
System.out.println("Fetched data from excel sheet is -- "+credentials[i][j]);
}
With
for(int j = 0; j<colm; j++)
{
credentials[i-1][j] = excelfile.getdata("LoginPage", i, j);
System.out.println("Fetched data from excel sheet is -- "+credentials[i-1][j]);
}

Unable to print verify in selenium datepicker value

I am new to selenium and I am trying to verify selected date in datepicker field but when I am executing this program it is printing else section, which it should not show. Kindly help to know where I am going wrong.
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;
public class tripadviser {
static WebDriver driver;
public static void main(String[] args) {
String start_date = "29-March 2017";
String[] splitter = start_date.split("-");
String start_day = splitter[0];
String start_month = splitter[1];
System.setProperty("webdriver.chrome.driver", "D:\\rakesh\\software\\selenium browser\\New folder\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.tripadvisor.in/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(By.id("rdoFlights")).click();
WebElement datepicker_ele = driver.findElement(By.id("metaCheckInSpan"));
datepicker_ele.click();
select_date_fun(start_day, start_month);
WebElement check_in_ele = driver.findElement(By.id("checkIn"));
String datepicker_expected_str = "29/3/2017";
if (check_in_ele.getText().equals(datepicker_expected_str)) {
System.out.println("Date selection is done succesfully");
} else {
System.out.println("Something went wrong");
}
driver.close();
}
public static void select_date_fun(String day, String month_year) {
List < WebElement > month_ele = driver.findElements(By.xpath(".//div[#class='calendar']/div[#class='month']/table/thead/tr/th[#class='caption']"));
for (int i = 0; i < month_ele.size(); i++) {
//System.out.println(month_ele.get(i).getText());
if (month_ele.get(i).getText().equals(month_year)) {
List < WebElement > day_ele = driver.findElements(By.xpath(".//div[#class='calendar']/div[#class='month'][1]/table/tbody/tr/td/a"));
for (WebElement j: day_ele) {
//System.out.println(j.getText());
if (j.getText().equals(day)) {
j.click();
return;
}
}
}
}
}
}
My question is resolved by using .getAttribute("value") instead of .getText()

Cannot Print names of all result links on first 5 pages of Google.com in Selenium

I am trying to print names of all result links on the first 5 pages on Google.com
Scenario is,
1) Go to www.google.com and search for something.
2) Print names of all result links on first 5 pages
I am able to print all the result links of first page and click next page link. But second page links are not printing. I think the reason may be with the xpath changing in second page. If so, how do I print all the links of 2nd 3rd 4th and 5th page.
Kindly help me in solving this solution.
package com;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
public class Exercise2 {
static WebDriver d;
public static void main(String[] args) throws InterruptedException {
ProfilesIni prop = new ProfilesIni();
FirefoxProfile seleniumProfile = prop.getProfile(("Selenium"));
d = new FirefoxDriver();
d.manage().window().maximize();
d.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
d.get("http://www.google.com");
Thread.sleep(5000);
d.findElement(By.name("q")).sendKeys("Selenium");
d.findElement(By.name("q")).sendKeys(Keys.ENTER);
Thread.sleep(5000);
//Print names of all result links on first page.
String part1 = "//div[#id='rso']/div[2]/div[";
String part2 = "]/div/h3/a";
for(int i=2;i<=5;i++){
String part3 = "//div[#id='navcnt']/table/tbody/tr/td[";
String part4 = "]";
int a = 1;
while(isElementPresent(part1+a+part2)){
String text = d.findElement(By.xpath(part1+a+part2)).getText();
System.out.println(text);
a++;
}
Thread.sleep(5000);
System.out.println("*************Next Page**********");
Thread.sleep(5000);
d.findElement(By.xpath(part3+i+part4)).click();
}
}
public static boolean isElementPresent(String xpathexp){
List<WebElement> allList = d.findElements(By.xpath(xpathexp));
//WebElement nextPages = d.findElement(By.xpath(nextPage1));
if(allList.size()==0)
{
return false;
}else{
return true;
}
}
}
List<WebElements> links = driver.findElements(By.tagName("a"));
for(int i = 0 ; i < 5 ; i ++)
{
string firstLink = links[i].getAttribute("href");
}
try following code.
package javaselenium;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
/**
*
* #author Muhammad USman
*/
public class JavaSelenium {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Hello Wrold");
GetUrls("Selenium");
}
public static ArrayList GetUrls(String keyWord)
{
FirefoxDriver driver;
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.get("https://www.google.com/?gws_rd=ssl");
WebElement qElement;
qElement = driver.findElement(By.name("q"));
qElement.sendKeys(keyWord);
qElement.sendKeys(Keys.ENTER);
try {
Thread.sleep(3*1000);
} catch (InterruptedException ex) {
Logger.getLogger(JavaSelenium.class.getName()).log(Level.SEVERE, null, ex);
}
//give number how mange pages you want to crawl
int nPageToCrawl=5;
List links;
links=new ArrayList();
for (int i = 0; i < nPageToCrawl; i++) {
if(i>0)
{
System.out.println("***Click on Next Page***");
//Click on Next Page
driver.findElement(By.id("pnnext")).click();
try {
Thread.sleep(3*1000);
} catch (InterruptedException ex) {
Logger.getLogger(JavaSelenium.class.getName()).log(Level.SEVERE, null, ex);
}
}
//it will get all links of pageLinks
List<WebElement> pageLinks = driver.findElements(By.cssSelector(".r>a"));
for (WebElement pageLink : pageLinks) {
links.add(pageLink.getAttribute("href"));
System.out.println(pageLink.getText());
System.out.println(pageLink.getAttribute("href"));
}
}
//close browser
driver.quit();
return (ArrayList) links;
}
}
if any issue then let me know.