I am trying to input the values to excel from web, having 2 columns and 9 rows, so that I will get the price and the description of 10 products from the web.
but Iam getting the Null pointer exception. Please any one help me out in clearing this error.
package samples;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
//import org.apache.commons.io.FileUtils;
//import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import java.text.ParseException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
//import org.openqa.selenium.OutputType;
//import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class A1 {
public static void main(String[] args) throws InterruptedException, ParseException, IOException, EncryptedDocumentException, InvalidFormatException
{
System.out.println("selenium");
WebDriver webdriver = new FirefoxDriver();
webdriver.manage().window().maximize();
webdriver.get("http://www.snapdeal.com");
webdriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
List<WebElement> alllinks = webdriver.findElements(By.tagName("a"));
int linkcnt = alllinks.size();
System.out.println("total links=" +linkcnt);
Actions action = new Actions(webdriver);
WebElement COG = webdriver.findElement(By.xpath("//span[text()='Computers, Office & Gaming']"));
WebElement EHD = webdriver.findElement(By.xpath("//span[text()='External Hard Drives']"));
action.moveToElement(COG).build().perform();
Thread.sleep(5000);
EHD.click();
webdriver.findElement(By.xpath("//label[#for='Capacity_s-1 TB']")).click();
Thread.sleep(5000);
webdriver.findElement(By.xpath("//a[contains(text(),'500 GB')]/..")).click();
Thread.sleep(5000);
webdriver.findElement(By.xpath("(//span[#class='price-collapse-arrow'])[1]/..")).click();
WebElement totalitems = webdriver.findElement(By.xpath("//span[#class='category-count']"));
String totalitemsvalue=totalitems.getText();
System.out.println(totalitemsvalue);
String value=totalitemsvalue.replaceAll(" Items","");
System.out.println(value);
try{
List<WebElement> productprice = webdriver.findElements(By.xpath("//div[#class='product-tuple-description']/div[2]"));
List<WebElement> productTitle = webdriver.findElements(By.xpath("//div[#class='product-desc-rating title-section-collapse']"));
int count=productprice.size();
int count1=productTitle.size();
System.out.println(count);
System.out.println(count1);
//int i=9;
// int j=9;
Thread.sleep(2000);
for (count=0;count<10;count++)
{
productprice = webdriver.findElements(By.xpath("//div[#class='product-tuple-description']/div[2]"));
// File srcfile=((TakesScreenshot)webdriver).getScreenshotAs(OutputType.FILE);
// FileUtils.copyFile(srcfile, new File("c:\\screenshot.png"));
Thread.sleep(2000);
String RupeesValue= productprice.get(count).getText();
System.out.println(RupeesValue);
Thread.sleep(2000);
productTitle = webdriver.findElements(By.xpath("//div[#class='product-tuple-description']/div[1]"));
Thread.sleep(2000);
String TitleValue= productTitle.get(count1).getText();
System.out.println(TitleValue);
Thread.sleep(2000);
FileInputStream fis = new FileInputStream("C:\\Users\\aa74231\\Desktop\\abc.xlsx");
Workbook wb = WorkbookFactory.create(fis);
Sheet sheet = wb.getSheet("Sheet1");
// Sheet sheet1 = wb.getSheet("Sheet1");
for (int i=0;i<2;i++)
{
Row row=sheet.getRow(count);
// Row row1=sheet.getRow(j);
Cell cell = row.createCell(count);
// Cell cell1 = row1.createCell(count1);
cell.setCellType(cell.CELL_TYPE_STRING);
//cell1.setCellType(cell1.CELL_TYPE_STRING);
if(i==0){
cell.setCellValue(productprice.get(count).getText());
}
else
{
cell.setCellValue(productTitle.get(count).getText());
}
//cell1.setCellValue(productTitle.get(count1).getText());
FileOutputStream fos=new FileOutputStream("C:\\Users\\aa74231\\Desktop\\abc.xlsx");
wb.write(fos);
fos.close();
wb.close();
}
}
} catch(Exception e){
e.printStackTrace();
}
}
}
exception which am getting is :
Exception in thread "main" java.lang.NullPointerException
at samples.learningold.main(learningold.java:97)
First of all your ProductTitle Xpath is not fetching all the product names from the list. I have updated that too.
Following code works well.
package samples;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
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;
import org.openqa.selenium.interactions.Actions;
public class X
{
#SuppressWarnings("resource")
public static void main(String[] args) throws InterruptedException, ParseException, IOException, EncryptedDocumentException, InvalidFormatException
{
System.out.println("selenium");
WebDriver webdriver = new FirefoxDriver();
webdriver.manage().window().maximize();
webdriver.get("http://www.snapdeal.com");
webdriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
List<WebElement> alllinks = webdriver.findElements(By.tagName("a"));
int linkcnt = alllinks.size();
System.out.println("total links=" +linkcnt);
Actions action = new Actions(webdriver);
WebElement COG = webdriver.findElement(By.xpath("//span[text()='Computers, Office & Gaming']"));
WebElement EHD = webdriver.findElement(By.xpath("//span[text()='External Hard Drives']"));
action.moveToElement(COG).build().perform();
Thread.sleep(5000);
EHD.click();
webdriver.findElement(By.xpath("//label[#for='Capacity_s-1 TB']")).click();
Thread.sleep(5000);
webdriver.findElement(By.xpath("//a[contains(text(),'500 GB')]/..")).click();
Thread.sleep(5000);
webdriver.findElement(By.xpath("(//span[#class='price-collapse-arrow'])[1]/..")).click();
Thread.sleep(5000);
WebElement totalitems = webdriver.findElement(By.xpath("//span[#class='category-count']"));
String totalitemsvalue=totalitems.getText();
System.out.println(totalitemsvalue);
String value=totalitemsvalue.replaceAll(" Items","");
System.out.println(value);
try
{
List<WebElement> productprice = webdriver.findElements(By.xpath("//div[#class='product-tuple-description']/div[2]"));
List<WebElement> productTitle = webdriver.findElements(By.xpath("//div[#class='product-tuple-description']/div[1]"));
int count=productprice.size();
int count1=productTitle.size();
System.out.println(count);
System.out.println(count1);
String[] productPriceList = new String[count];
String[] productTitleList = new String[count];
Thread.sleep(2000);
for(int k =0; k<count; k++)
{
System.out.println(productprice.get(k).getText());
productPriceList[k]=productprice.get(k).getText();
System.out.println(productTitle.get(k).getText());
productTitleList[k]=productTitle.get(k).getText();
}
File file= new File("C:\\Users\\XX\\Downloads\\snapdeal.xlsx"); // give your file path
FileInputStream inputStream = new FileInputStream(file);
Workbook sampleWorkbook=null;
sampleWorkbook=new XSSFWorkbook(inputStream);
Sheet sheet = sampleWorkbook.getSheet("Sheet1");
for(int t=0;t<count;t++)
{
Row row = sheet.createRow(t);
Cell cell = row.createCell(0); // create column 1
cell.setCellValue(productPriceList[t].toString());
Cell cell1 = row.createCell(1); // create column 2
cell1.setCellValue(productTitleList[t].toString());
inputStream.close();
FileOutputStream outputStream = new FileOutputStream(file);
sampleWorkbook.write(outputStream);
System.out.println("Data written to Excel successful");
outputStream.close();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Related
I am automating hybrid application i.e. Desktop and WebApplication. We have desktop application in which some of pages are integrated using WebPages and some one pages are in desktop application. Below is the code which I have used to open Desktop Application. And its opening the application successfully. But When I am going to print resource list size, it comes 'null' where locator for resourcelist is showing correct count in chrome browser. I can login successfully using winium driver instance. After logged in, list of resources are present which I integrated in webpage.
Let me know if I am doing wrong in given code?
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.winium.DesktopOptions;
import org.openqa.selenium.winium.WiniumDriver;
import org.openqa.selenium.winium.WiniumDriverService;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
public class VMSWiniumBaseDriver {
public WiniumDriver driver;
String applicationPath = "C:\\Users\\prashantn\\Downloads\\Publish\\ABC.exe";
#Parameters({ "windowsPlatform" })
#BeforeClass(alwaysRun = true)
public void initialize(String browser) throws IOException, InterruptedException {
if (browser.equalsIgnoreCase("desktop")) {
try {
WiniumDriverService service;
DesktopOptions option;
option = new DesktopOptions();
option.setApplicationPath(applicationPath);
File driverPath = new File(System.getProperty("user.dir") + File.separator + "driver" + File.separator
+ "Winium.Desktop.Driver.exe");
service = new WiniumDriverService.Builder().usingDriverExecutable(driverPath).usingPort(9999)
.withVerbose(true).withSilent(false).buildDesktopService();
try {
service.start();
} catch (IOException e) {
System.out.println("Exception while starting WINIUM service");
e.printStackTrace();
}
driver = new WiniumDriver(service, option);
} catch (Exception e) {
System.out.println(e);
}
}
}
#AfterClass(alwaysRun = true)
public void TeardownTest() {
if (null == driver) {
driver.close();
driver.quit();
}
}
public WiniumDriver getDriver() {
return driver;
}
}
Here is
CommonUtilities.Java
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.concurrent.ThreadLocalRandom;
import org.openqa.selenium.WebDriver;
import org.sikuli.hotkey.Keys;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;
import org.sikuli.script.ScreenImage;
import dataproviders.VMSConfigFileReader;
import managers.VMSWiniumBaseDriver;
public class CommonUtilities extends VMSWiniumBaseDriver {
public WebDriver getWebDriverInstance() {
WebDriver webDriver = (WebDriver) driver;
return webDriver;
}
}
LoginPage.java
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.winium.WiniumDriver;
import utilities.CommonUtilities;
public class LoginPage{
#FindBy(id = "PART_EditableTextBox")
WebElement userName;
#FindBy(id = "TextBlock_Password")
WebElement passwordInput;
#FindBy(id = "LoginButton")
WebElement loginButton;
#FindBy(xpath = "//dd[contains(#class,'vms-tree-enabled')]/span[#class='vms-treeview-label'][#title!='Removed channels'][#title!='Unassociated']")
List<WebElement> resourcesList;
public void getResourcesList() {
CommonUtilities commonUtilities = new CommonUtilities();
// System.out.println("Page Source :: "+commonUtilities.getWebDriverInstance());
List<WebElement> list = commonUtilities.getWebDriverInstance().findElements(By.xpath(
"//dd[contains(#class,'vms-tree-enabled')]/span[#class='vms-treeview-label'][#title!='Removed channels'][#title!='Unassociated']"));
System.out.println("Resources Size :: " + list.size());
for (int i = 0; i < resourcesList.size(); i++) {
System.out.println("Resource Name :: " + resourcesList.get(i).getText());
}
}
}
Exception Log:
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebDriver.findElements(org.openqa.selenium.By)" because the return value of "utilities.CommonUtilities.getWebDriverInstance()" is null
at pageobjects.LoginPage.getResourcesList(LoginPage.java:57)
at testcases.AppLaunchTest.selectLayOutBasic1(AppLaunchTest.java:62)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:132)
at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:599)
at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:174)
at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:822)
at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:147)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.testng.TestRunner.privateRun(TestRunner.java:764)
at org.testng.TestRunner.run(TestRunner.java:585)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:384)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:378)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:337)
at org.testng.SuiteRunner.run(SuiteRunner.java:286)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1218)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
at org.testng.TestNG.runSuites(TestNG.java:1069)
at org.testng.TestNG.run(TestNG.java:1037)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
I am trying to fetch drop down list values and insert onto an excel file.
I have written a code, but it is showing an error on the page.
Error shown as "java.lang.NullPointerException".
Below is the code written :-
package test.neha;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
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.*;
import org.testng.annotations.Test;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Dropdown_extraction {
public static WebDriver driver;
WebDriverWait wait;
XSSFWorkbook workbook;
XSSFSheet sheet;
XSSFCell cell;
#Test
public void list_items() throws EncryptedDocumentException, InvalidFormatException, IOException
{
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
driver=new ChromeDriver();
driver.get("file:///C:/Users/neha.sharma/Desktop/File.html");
//driver.manage().window().maximize();
File src=new File("D:\\Drop_values.xlsx");
WebElement Element=driver.findElement(By.xpath("html/body/form/fieldset/p/select"));
Element.click();
FileInputStream fr=new FileInputStream(src);
workbook = (XSSFWorkbook) WorkbookFactory.create(fr);
XSSFSheet sh = workbook.getSheetAt(0);
List<WebElement> L= (List) driver.findElements(By.xpath("html/body/form/fieldset/p/select"));
for(WebElement e:L)
{
String value=e.getText();
System.out.println("Print the values as below:"+value);
System.out.println("Values are:"+ e.getText());
Row row=sh.getRow(0);
Cell[] cell=new Cell[10];
if(row==null)
{
for(int i=1;i<=10;i++)
{
cell[i]=row.createCell(i);
}
if(cell[1]==null)
{
cell[1].setCellType(Cell.CELL_TYPE_NUMERIC);
cell[1].setCellValue(value);
}
if(cell[2]==null)
{
cell[2].setCellType(Cell.CELL_TYPE_NUMERIC);
cell[2].setCellValue(value);
}
}
/*sh.getRow(1).createCell(0).setCellValue(value);
sh.getRow(2).createCell(1).setCellValue(value);
sh.getRow(3).createCell(2).setCellValue(value);
sh.getRow(4).createCell(3).setCellValue(value);
*/
FileOutputStream Output = new FileOutputStream(src);
workbook.write(Output);
Output.close();
}
/*Select element_list=new Select(driver.findElement(By.xpath("html/body/form/fieldset/p/select")));
element_list.selectByVisibleText("Apple");*/
}
}
Could anyone let me know the solution of this error. The error shown mostly in "Create Cell code" .
Please help me out.
This script is to read data from excel and use it in selenium script. This uses Apache POI to read the data, store it in variables and use it.
You can try following code. I have taken facebook as sample application.
package testPackage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
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.testng.annotations.*;
import org.testng.annotations.DataProvider;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class ExcelReadingwithDP {
WebDriver driver;
#BeforeTest
public void OpenApp()
{
System.setProperty("webdriver.chrome.driver", "E:/Selenium/Webdriver/Softwares/chromedriver.exe");
driver = new ChromeDriver();
driver.navigate().to("http://facebook.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#Test(dataProvider="empLogin")
public void login(String username, String password)
{
WebElement login1 = driver.findElement(By.id("email"));
login1.clear();
login1.sendKeys(username);
WebElement passwd=driver.findElement(By.id("pass"));
passwd.clear();
passwd.sendKeys(password);
driver.findElement(By.xpath("//*[#id='u_0_q']")).click();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
WebElement back = driver.findElement(By.xpath("//*[#id='blueBarDOMInspector']/div/div[1]/div/div/h1/a/i"));
back.click();
}
#DataProvider(name="empLogin")
public Object[][] logindata()
{
Object[][] arrayobject = getexceldata("E://Deepak/IntranetLogin.xls","Sheet1");
return arrayobject;
}
public String[][] getexceldata(String filename, String sheetname)
{
String[][] arrayexceldata = null;
try
{
FileInputStream fis = new FileInputStream(filename);
Workbook wb = Workbook.getWorkbook(fis);
Sheet sh = wb.getSheet(sheetname);
int row = sh.getRows();
int col = sh.getColumns();
arrayexceldata = new String[row-1][col];
for (int i=1;i< row;i++)
{
for(int j=0;j<col;j++)
{
arrayexceldata[i-1][j]=sh.getCell(j,i).getContents();
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
return arrayexceldata;
}
}
/*
* Download Apache POI from https://www.apache.org/dyn/closer.lua/poi/release/bin/poi-bin-3.16-20170419.zip
*
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
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;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class FormFill {
public static void main(String[] args) throws Exception {
try {
FileInputStream fileInputStream = new FileInputStream("C:\\data.xls");
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
HSSFSheet worksheet = workbook.getSheet("sheet1");
HSSFRow row1 = worksheet.getRow(0);
HSSFCell cellA1 = row1.getCell((short) 0);
String a1Val = cellA1.getStringCellValue();
HSSFCell cellB1 = row1.getCell((short) 1);
String b1Val = cellB1.getStringCellValue();
System.out.println("A1: " + a1Val);
System.out.println("B1: " + b1Val);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String url = "http://thedemosite.co.uk/addauser.php";
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get(url);
//Thread.sleep(30000);
driver.findElement(By.name("username")).sendKeys(a1Val);
driver.findElement(By.name("password")).sendKeys(b1Val);
}
}
I feel csv is better than Excel because Excel more time to read the data but csv is fast.
private static final String CSV_SEPARATOR = ",(?=(?:[^\"]\"[^\"]\")[^\"]$)";
public List<String[]> parseFile(String fileName) {
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
br.readLine(); // skip header;
String line = br.readLine();
List<String[]> lines = new ArrayList();
while (line != null) {
//System.out.println(line.toString());
lines.add(line.split(CSV_SEPARATOR));
line = br.readLine();
}
return lines;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
we have a webpage with 2 date calender one is a current date the other is referencedate which autoupdates itself to display a day less than the current date.
issue-After selecting a date from a calender using webdriver click the other
calender which had to update the date automatically, does not update anymore.
The same actions if performed manually works.
Has anybody faced a similiar issue, this has become a blocker since with the autoupdate not working the entire application workflow fails.
removed sensitive data
package pages;
import java.util.Calendar;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.SendKeysAction;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.thoughtworks.selenium.Selenium;
import com.thoughtworks.selenium.webdriven.SeleniumMutator;
import com.thoughtworks.selenium.webdriven.commands.SeleniumSelect;
import utils.Waitutils;
public class CalenderPage {
WebDriver driver;
static WebDriverWait wait;
public CalenderPage (WebDriver driver){
this.driver = driver;
}
public void cobDatepick(String date){
int count=0;
WebElement cob =driver.findElement(By.xpath("//*[#id='mainview']/div/div[2]/div[1]/div/options-panel-directive/div[2]/div[1]/div/div[1]/date-picker/div[2]/div/span"));
cob.click();
WebElement mLink = driver.findElement(By.xpath("//button[contains(#id,'datepicker')]"));
String date_dd_MM_yyyy[] = (date.split(" ")[0]).split("/");
int yearDiff = Calendar.getInstance().get(Calendar.YEAR) - Integer.parseInt(date_dd_MM_yyyy[2]);
mLink.click();
WebElement pLink = driver.findElement(By.xpath("//*[#id='mainview']/div/div[2]/div[1]/div/options-panel-directive/div[2]/div[1]/div/div[1]/date-picker/div[2]/div/ul/li[1]/div/table/thead/tr[1]/th[1]/button/i"));
if(yearDiff>0){
for(int i=0;i<yearDiff;i++){
pLink.click();
}
}
List<WebElement> months1 = driver.findElements(By.xpath("//*[#id='mainview']/div/div[2]/div[1]/div/options-panel-directive/div[2]/div[1]/div/div[1]/date-picker/div[2]/div/ul/li[1]/div/table/tbody/tr/td"));
months1.get(Integer.parseInt(date_dd_MM_yyyy[1])-1).click();
List<WebElement> dates = driver.findElements(By.xpath("//*[#id='mainview']/div/div[2]/div[1]/div/options-panel-directive/div[2]/div[1]/div/div[1]/date-picker/div[2]/div/ul/li[1]/div/table/tbody/tr//td"));
int total_nodes = dates.size();
for(int i=0; i<total_nodes; i++)
{
String dat = dates.get(i).getText();
if(dat.equals(date_dd_MM_yyyy[0])&& count>0)
{
dates.get(i).click();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.document.getElementById('date-picker-to').setAttribute('value', '30/06/2016');");
}
if(dat.equals(date_dd_MM_yyyy[0]))
{
count++;
}
}
}
}
The above class is called in the testscript
#BeforeTest
public void setup() throws Exception{
driver = new AppDriver("ie").getDriver();
driver.get("https://xyz");
driver.manage().window().maximize();
onCalenderPage = new CalenderPage (driver);
Waitutils.waitforCompletion(9000L);
}
#Test
public void test(){
onCalenderPage.cobDatepick("30/06/2016");
}
I'm i\using webdriver version2.41 and browser is Firefox 28. I'm trying to find a listcount of elements present in the drop down list of a auto suggest textbox.Ex: in Google.co.in page i'm writing Banga to get the suggestions for Bangalore. Once i get the suggestion list then i want to dispay all the Auto suggested text on the screen. I have written the code, but don't know why its not working. I'm anew bie to selenium webdriver. Please help me. Here is my code :
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.firefox.FirefoxDriver;
public class test {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.co.in");
driver.findElement(By.id("gbqfq")).sendKeys("Banga");
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
List<WebElement> lstobj = driver.findElements(By.xpath("//div[#class='gsq_a']/table/tbody/tr/td/span/b"));
System.out.println(lstobj.size());
for (int i = 0; i<lstobj.size();i++)
{
String p= lstobj.get(i).getText();
System.out.println(p);
}
}
}
I hope this helps u..
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.firefox.FirefoxDriver;
public class google{
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.co.in");
driver.findElement(By.id("gbqfq")).sendKeys("Banga");
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
WebElement parent=driver.findElement(By.className("gssb_e"));
List<WebElement> child = parent.findElements(By.tagName("div"));
int size=child.size();
System.out.println(size);
for (int i =1; i<=size;i++)
{
String p= driver.findElement(By.xpath("//*[#id='gsr']/table/tbody/tr[1]/td[2]/table/tbody/tr["+i+"]/td/div/table/tbody/tr/td[1]")).getText();
System.out.println(p);
driver.close();
}
}
}
Edited the xpath used by you and the way you retrieved text :
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.firefox.FirefoxDriver;
public class test {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.co.in");
driver.findElement(By.id("gbqfq")).sendKeys("Banga");
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
List<WebElement> lstobj = driver.findElements(By.xpath("//table[#class='gssb_m']/tbody/tr"));
System.out.println(lstobj.size());
for (int i = 0; i<lstobj.size();i++)
{
String p= lstobj.get(i).findElement(By.xpath("//span")).getText();
System.out.println(p);
}
}
driver.get("https://www.google.co.in/");
driver.findElement(By.xpath("//input[#class='gLFyf gsfi']")).sendKeys("Banga");
//This will also work USE descendant to get all child element
List<WebElement> printlist = driver.findElements(By.xpath("//ul[#role='listbox']//li/descendant::div[#class='sbl1']"));
System.out.println(printlist.size());
for ( WebElement list: printlist) {
//if you want to specify condition here you can
System.out.println(list.getText());
}