I am trying to understand and practice reading from and Excel file and send login credential to a webpage. In the test excel file I have 2 usernames and 2 password. The 1st set works properly(meaning being sent to webpage fields), however during the 2nd set I get the following problem :
Exception in thread "main" org.openqa.selenium.NoSuchWindowException: Window not found. The browser window may have been closed.
Command duration or timeout: 221 milliseconds
Here is the code:
public class EX1 {
public static WebDriver driver;
public int cellNo;
public WebDriver utility(String browser, String url){
if(browser.equals("ff")){
driver= new FirefoxDriver();
}
driver.get(url);
return driver;
}
public ArrayList<String> readExcel(int cellNo) throws IOException{
FileInputStream fis = new FileInputStream("C:\\dev\\Petco.xls");
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator= sheet.iterator();
rowIterator.next();// Escapes the Header
ArrayList<String> list= new ArrayList<String>(); //After reading the data I will add them to String list
while(rowIterator.hasNext()){
//list.add(rowIterator.next().getCell(0).getStringCellValue());//will just print 1st username
//list.add(rowIterator.next().getCell(1).getStringCellValue()); // will just print 1st password
//The above code with hardcoded 0,1- I can't call them in below getPage function. I will
//make a parameter for this method which I will pass, cellNo is a parameter instead of 0,1
list.add(rowIterator.next().getCell(cellNo).getStringCellValue());//will just print 1st username
}
return list;
}
public void loginPage(String uname,String psd){
WebElement username=driver.findElement(By.xpath("//input[#id='WC_AccountDisplay_FormInput_logonId_In_Logon_1']"));
WebElement password=driver.findElement(By.xpath("//input[#id='WC_AccountDisplay_FormInput_logonPassword_In_Logon_1']"));
WebElement login_btn=driver.findElement(By.xpath("//button[contains(#id,'WC_AccountDisplay_links_2')]"));
username.sendKeys(uname);
password.sendKeys(psd);
login_btn.click();
}
public void getPage() throws InterruptedException, IOException{
EX1 e= new EX1();
e.utility("ff", "https://www.petco.com/shop/AjaxLogonForm?catalogId=10051&myAccountActivePage=myAccount&myAcctMain=1&langId=-1&storeId=10151");
EX1 e1=PageFactory.initElements(driver, EX1.class);
//Will use the list from above that contains the login information here
ArrayList<String> username=e.readExcel(0); //-- reading the 1st column which has user name
ArrayList<String> password=e.readExcel(1); //-- reading the 1st column which has user name
for(int i=0; i<username.size(); i++){ //-- I want to read excel multiple times which is why the for loop
e1.loginPage(username.get(i), password.get(i));
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.close();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
EX1 e= new EX1();
e.getPage();
//e.readExcel();
}
}
I have tried Thread.sleep, driver.quit() those modifications did not have any impact.
Let me know what else I can try, thanks n advance for your time.
Error seems browser window closed after first iteration...Observe your test case while running...see it's closing browser window after first iteration i.e. driver.close();..removing this line and putting somewhere after for loop completion, may help you. e.g.
for(int i=0; i<username.size(); i++){ //-- I want to read excel multiple times which is why the for loop
e1.loginPage(username.get(i), password.get(i));
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
driver.close();
Related
I would like to save number to a file when element is displayed and then test should be passed.
Else if element is not visible test should be also passed but number shoudn't be save into a file.
Saving number when element is displayed works fine, also when element is not displayed test don't save it into file so this also works fine.
Two problems:
Selenium search for element when is not displayed approx... 15s? It's too long, how to reduce this time? Use Waits?
Most important, if element is not displayed test fails, I'd like to pass it because the whole process is done and waiting for this element and saving number is additional thing.
public void saveNumberIntoFile(String fileNumber) throws IOException {
if(messageInfo.isDisplayed())
{BufferedWriter writer = new BufferedWriter(
new FileWriter("C:\\Users\\xxx\\Documents\\samplefile.txt", true) //Set true for append mode
);
writer.newLine(); //Add new line
writer.write(fileNumber);
writer.close();}
}
You need WebDriverWait and ExpectedConditions to handle wait element, like this:
new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOfElementLocated(By.name("")));
Replace By.name("") with the locator that you initialed on messageInfo.
15 in seconds, if the element is located it will not wait until 15s.
But if within a certain time period that we have determined the element is not found, it will return an error:
NoSuchElementException: Cannot locate an element using....
And your test will stop, so you need handle with try/catch.
public void saveNumberIntoFile(String fileNumber) throws IOException {
try {
new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOfElementLocated(By.name("")));
BufferedWriter writer = new BufferedWriter(
new FileWriter("C:\\Users\\xxx\\Documents\\samplefile.txt", true) //Set true for append mode
);
writer.newLine(); //Add new line
writer.write(fileNumber);
writer.close();
} catch (NoSuchElementException e) {
// TODO: handle exception
}
}
I am having trouble printing all the values from a list.
Below is the complete code:
public class TestCase1{
private static XSSFWorkbook wb;
private static XSSFSheet sh;
private static File file;
static int i=0;
public static void main(String args[]) throws Exception
{
file = new File("D:\\Eclipse and workspace\\workspace\\SeleniumPractice\\IMDBTestCase1.xlsx");
FileInputStream fIs = new FileInputStream(file);
wb = new XSSFWorkbook(fIs);
sh = wb.getSheet("Sheet1");
sh.createRow(i);
System.setProperty("webdriver.gecko.driver", "D:\\Eclipse and workspace\\eclipse\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://www.imdb.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Actions action = new Actions(driver);
action.moveToElement(driver.findElement(By.id("navTitleMenu"))).build().perform();
Thread.sleep(5000);
driver.findElement(By.xpath("//div[#id='navMenu1']/div[2]/ul[1]/li[6]/a")).click();
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//table[#class='chart full-width']/thead/tr/th[2]")));
WebElement elem1 = driver.findElement(By.xpath("//table[#class='chart full-width']/thead/tr/th[2]"));
String title = elem1.getText();
write(0,0,title);
WebElement elem2 = driver.findElement(By.xpath("//table[#class='chart full-width']/thead/tr/th[3]"));
String rating = elem2.getText();
write(0,1,rating);
i++;
List <WebElement> elements = driver.findElements(By.className("lister-list"));
for(WebElement element : elements)
{
String str1 = element.findElement(By.xpath("//tbody[#class='lister-list']/tr["+i+"]/td[2]")).getText();
System.out.println(str1);
//write(i,0,elem3.getText());
String str2 = element.findElement(By.xpath("//tbody[#class='lister-list']/tr["+i+"]/td[3]")).getText();
System.out.println(str2);
//write(i,1,elem4.getText());
i++;
}
System.out.println("Success");
wb.close();
}
public static void write(int row, int col, String val) throws Exception
{
FileOutputStream fos = new FileOutputStream(file);
sh.createRow(row+1);
sh.getRow(row).createCell(col).setCellValue(val);
wb.write(fos);
}
}
Now in the below part,
List <WebElement> elements = driver.findElements(By.className("lister-list"));
for(WebElement element : elements)
{
String str1 = element.findElement(By.xpath("//tbody[#class='lister-list']/tr["+i+"]/td[2]")).getText();
System.out.println(str1);
//write(i,0,elem3.getText());
String str2 = element.findElement(By.xpath("//tbody[#class='lister-list']/tr["+i+"]/td[3]")).getText();
System.out.println(str2);
//write(i,1,elem4.getText());
i++;
}
Here the output is printing only this:
1. The Shawshank Redemption (1994)
9.2
Success
I want to print all the movies names and their ratings but I am not sure why it is printing only the first one.
Also if I use the below for loop, it will print all the names and ratings but I want them separately as I want to store them in an excel file.
for(WebElement element : elements)
{
System.out.println(element.getText());
}
PS: The real thing here I am trying to do is to store the movies names and their ratings in an excel file.
If you debug your elements list, you will find that it only has 1 element. You need to specify the tr elements in the tbody to return multiple elements.
I prefer to get elements by CSS selectors as I find it easier to write.
This will get what you want...
List <WebElement> elements = driver.findElements(By.cssSelector(".lister-list > tr"));
for(WebElement element : elements)
{
String title = element.findElement(By.cssSelector(".titleColumn")).getText();
System.out.println(title);
String rating = element.findElement(By.cssSelector(".ratingColumn.imdbRating")).getText();
System.out.println(rating);
}
UPDATE: Here is the implementation using XPATH.
List <WebElement> elements = driver.findElements(By.xpath("//tbody[#class='lister-list']//tr"));
for(WebElement element : elements)
{
String title = element.findElement(By.xpath("td[#class='titleColumn']")).getText();
System.out.println(title);
String rating = element.findElement(By.xpath("td[contains(#class, 'ratingColumn') and contains(#class, 'imdbRating')]")).getText();
System.out.println(rating);
}
Selenium WebDriver:
I have a excel sheet with users having multiple skills, the single user has multiple skills with multiple rows and I am entering that data dynamically in the portal by checking the usernames from home page in UI and name in excelsheet, if it matches it clicks the user in the UI where it navigates to other page and other function returns the no of rows user has in excel sheet and fetches the data row by row cell by cell for all rows user has and adds in the portal one by one.
Now when clicked on home page to go back and perform the operation where the webelements is left over to verify the other users match for the remaining, it is throwing staleelement exception.
Error shown:
Element not found in cache perhaps the page has changed after looked.
Error line:
String [] str = webElement.getText().split("\n");
I tried thread.sleep before clicking element, I tried try/catch but nothing is working, as I need other user data which has in Excel sheet to be compared with the remaining web element which is user names and click the next match to enter the matching user data again row by row cell by cell.
Please help, I am trying this from past 4 days and couldn’t figure out how to get continue further to get the others users data to enter in portal.
public static void main(String[] args) throws Exception {
WebElement NamePath=driver.findElement(By.xpath(ReadPropertyFile.readProperty("ClickNamePath")));
java.util.List<WebElement> ListPath1 = driver.findElements(By.xpath((ReadPropertyFile.readProperty("ClickNamePath"))));
Thread.sleep(3000);
Iterator<WebElement> itWebelement = ListPath1.iterator();
while(itWebelement.hasNext())
{
WebElement webElement = itWebelement.next();
String [] str = webElement.getText().split("\n");
String var= str[0];
System.out.println(var);
String FilePath1= "D:\\pcdp10012016_demo.xlsx";
FileInputStream inputStream = new FileInputStream(new File(FilePath1));
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
XSSFSheet sheet1= wb.getSheetAt(0);
List<EmployeePCDPDTO> pcdpDtoObject=ReadExcelData.ReadData(sheet1, var);
if(!pcdpDtoObject.isEmpty()){
webElement.click();
Iterator<EmployeePCDPDTO> itEmployeepcdpList = pcdpDtoObject.iterator();
while(itEmployeepcdpList.hasNext())
{
EmployeePCDPDTO employeePCDPDTO = itEmployeepcdpList.next();
Thread.sleep(3000);
WebElement Addbtn=driver.findElement(By.xpath(ReadPropertyFile.readProperty("AddSkillPath")));
Addbtn.click();
Thread.sleep(3000);
//select SkillType
WebElement s= driver.findElement(By.xpath(".//*[#id='skillTypeDropdown']"));
Select oselect= new Select(s);
oselect.selectByValue(employeePCDPDTO.getSkillType());
Thread.sleep(3000);
driver.findElement(By.xpath(".//*[#id='skillName']")).clear();
driver.findElement(By.xpath(".//*[#id='skillName']")).sendKeys(employeePCDPDTO.getSkillName());
Thread.sleep(3000);
//store button
driver.findElement(By.xpath(".//*[#id='add-edit-box']/div[7]/div/button[2]")).click();
}
//Home page path in UI
Thread.sleep(3000);
//home page button
driver.findElement(By.xpath(".//*[#id='app']/div/div/div[1]/ol/li[1]/a")).click();
Thread.sleep(5000);
}
}
}
}
I have changed few lines. Please try the following code and let me know.
public static void main(String[] args) throws Exception {
WebElement NamePath=driver.findElement(By.xpath(ReadPropertyFile.readProperty("ClickNamePath")));
java.util.List<WebElement> ListPath1 = driver.findElements(By.xpath((ReadPropertyFile.readProperty("ClickNamePath"))));
Thread.sleep(3000);
// Iterator<WebElement> itWebelement = ListPath1.iterator();
//while(itWebelement.hasNext())
for(int i=0; i < ListPath1.size();i++){
WebElement webElement = itWebelement.get(i);
String [] str = webElement.getText().split("\n");
String var= str[0];
System.out.println(var);
String FilePath1= "D:\\pcdp10012016_demo.xlsx";
FileInputStream inputStream = new
FileInputStream(new File(FilePath1));
XSSFWorkbook wb = new XSSFWorkbook(inputStream);
XSSFSheet sheet1= wb.getSheetAt(0);
List<EmployeePCDPDTO> pcdpDtoObject=ReadExcelData.ReadData(sheet1, var);
if(!pcdpDtoObject.isEmpty()){ webElement.click(); Iterator<EmployeePCDPDTO> itEmployeepcdpList = pcdpDtoObject.iterator(); while(itEmployeepcdpList.hasNext()) { EmployeePCDPDTO employeePCDPDTO = itEmployeepcdpList.next(); Thread.sleep(3000); WebElement Addbtn=driver.findElement(By.xpath(ReadPropertyFile.readProperty("AddSkillPath"))); Addbtn.click(); Thread.sleep(3000); //select SkillType WebElement s= driver.findElement(By.xpath(".//*[#id='skillTypeDropdown']")); Select oselect= new Select(s); oselect.selectByValue(employeePCDPDTO.getSkillType()); Thread.sleep(3000); driver.findElement(By.xpath(".//*[#id='skillName']")).clear(); driver.findElement(By.xpath(".//*[#id='skillName']")).sendKeys(employeePCDPDTO.getSkillName()); Thread.sleep(3000); //store button driver.findElement(By.xpath(".//*[#id='add-edit-box']/div[7]/div/button[2]")).click(); } //Home page path in UI Thread.sleep(3000); //home page button driver.findElement(By.xpath(".//*[#id='app']/div/div/div[1]/ol/li[1]/a")).click(); Thread.sleep(5000); } }ListPath1 = driver.findElements(By.xpath((ReadPropertyFile.readProperty("ClickNamePath")))); } }
for (int i = 0; i < ListPath1.size(); i++) {
count++;
if(count>1){
for(int j=0;j<=2;j++)
{
try{
java.util.List<WebElement> ListPath2 = driver.findElements(By.xpath((ReadPropertyFile.readProperty("ClickNamePath"))));
webElement = ListPath2.get(count-1);
String[] str = webElement.getText().split("\n");
var = str[0];
System.out.println(var);
break;
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}else{
webElement = ListPath1.get(i);
String[] str = webElement.getText().split("\n");
var = str[0];
System.out.println(var);
}
I'm trying to read a CSV file containing Mail IDs and Passwords using java in Selenium .After reading it, I need to login to each of these mail ids in the same browser. I have given six usernames and passwords in my CSV file. While executing, its not executing from the third login onwards.
Error is shown like this:
Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//*[#id='Email']"} Command duration or timeout: 17 milliseconds.
I'm using Firefox browser. Below is my entire :
public static void main(String[] args) throws Exception {
//csv reader aswathy -start
CSVReader reader = new CSVReader(new FileReader("/home/user/Documents/UrmilaDocs/CSV PAck/testCSV.csv"));
String [] nextLine;
WebDriver driver = new FirefoxDriver();
String appUrl = "https://accounts.google.com";
driver.get(appUrl);
driver.manage().window().maximize();
while ((nextLine = reader.readNext())!= null){
String user_name = nextLine[0];
String pass_word = nextLine[1];
System.out.println("Username: " + user_name);
System.out.println("Password: " + pass_word);
// //stackoverflow
// WebDriver driver = new FirefoxDriver();
// String appUrl = "https://accounts.google.com";
// driver.get(appUrl);
// driver.manage().window().maximize();
WebElement username = driver.findElement(By.xpath(".//*[#id='Email']"));
username.clear();
username.sendKeys(user_name);
driver.findElement(By.xpath(".//*[#id='next']")).click();
Thread.sleep(5000);
//try
try{
WebElement password = driver.findElement(By.xpath(".//*[#id='Passwd']"));
password.clear();
password.sendKeys( pass_word);
driver.findElement(By.xpath(".//*[#id='signIn']")).click();
Thread.sleep(8000);
//click on 'Google Apps' icon
driver.findElement(By.xpath(".//*[#id='gbwa']/div[1]/a")).click();
Thread.sleep(10000);
//Click on 'Gmail' icon to navigate to inbox page
driver.findElement(By.xpath(".//*[#id='gb23']/span[1]")).click();
Thread.sleep(10000);
System.out.println("Login Success");
//Click on user name first letter circle icon
driver.findElement(By.xpath(".//*[#id='gb']/div[1]/div[1]/div[2]/div[4]/div[1]/a/span")).click();
Thread.sleep(5000);
//click on 'Signout' button
driver.findElement(By.xpath(".//*[#id='gb_71']")).click();
Thread.sleep(10000);
System.out.println("Logout Success");
/*click on 'Signin with a different account ' option (since, after signing out from
// the first user, he page is navigated to password entry page, which is supposed to navigate to
// username/mailid entry page */
driver.findElement(By.xpath(".//*[#id='account-chooser-link']")).click();
Thread.sleep(10000);
// /* In 'Choose an Account page', Click on 'Add Account' button */
driver.findElement(By.xpath(".//*[#id='account-chooser-add-account']")).click();
Thread.sleep(10000);
//
}catch(Exception e)
{
System.out.println("Login failed!");
}// catch closed
// //closing driver & firefox
//driver.close();
//System.exit(0);
//end
} //while end
// //closing driver & firefox
// driver.close();
// //csv reader aswathy -end
System.exit(0); //closing firefox
}
}
I hope the problem is that, after 2 or 3 logins the page is not loading properly, thats why, its showing time-out and the xpath is also not getting detected. so, try to use waitForPageToLoad when trying to access gmail.
For fetching data excel file:
put excel data in ArrayList:
ArrayList<String> AL=new ArrayList<String>();
public static void fn_FetchExcelData(int row_num) throws IOException{
String WbookPath=TestDataPath;
String SheetName=TestDataSheetName;
File FileObj=new File(WbookPath);
FileInputStream FIS=new FileInputStream(FileObj);
#SuppressWarnings("resource")
Workbook WBookObj=new XSSFWorkbook(FIS);
Sheet SheetObj=WBookObj.getSheet(SheetName);
Row FstRowObj=SheetObj.getRow(0);
int cellCount=FstRowObj.getLastCellNum();
Row RowObj=SheetObj.getRow(row_num);
for(int i=0;i<=cellCount-1;i++){
Cell fstcellObj=FstRowObj.getCell(i,Row.CREATE_NULL_AS_BLANK);
String ColumnName=fstcellObj.getStringCellValue();
Cell reqCellObj=RowObj.getCell(i, Row.CREATE_NULL_AS_BLANK);
String reqRowCellValue=null;
if(reqCellObj.getCellType()==Cell.CELL_TYPE_STRING){
reqRowCellValue=reqCellObj.getStringCellValue();
}else if(reqCellObj.getCellType()==Cell.CELL_TYPE_NUMERIC){
Double dblColumnName=reqCellObj.getNumericCellValue();
Integer intColumnName =dblColumnName.intValue();
reqRowCellValue=intColumnName.toString(intColumnName);
}
if(ColumnName.trim().equalsIgnoreCase("")==false && ColumnName!=null){
AL.put(ColumnName,reqRowCellValue);
}
}
}
Get data from ArrayList:
int i;
int loginid=AL.size();
for(i=0;i<loginid;i++){
System.out.println(AL.get(i));
DriverObj.findElement(By.id("Username ID")).clear();
DriverObj.findElement((By.id("Username ID"))).sendKeys(AL.get(i));
DriverObj.findElement(By.id("password")).clear();
DriverObj.findElement((By.id("password"))).sendKeys("123456");
DriverObj.findElement(By.name("Button")).click();
Here is my code to click a simple login button on this Website
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Reports {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("https://platform.drawbrid.ge");
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
driver.findElement(By.xpath(".//*[#id='_loginButton']")).click();
}
}
I am getting following error:
Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with
Command duration or timeout: 2.05 seconds
You have two buttons with given xpath on this page, first is not visible, thats why you are getting ElementNotVisibleException
One is under <div class="loginPopup">
Second (the one you need) is under <div class="page">
So change your xpath to look like this, and it will fix your problem:
By.xpath("//div[#class='page']//div[#id='_loginButton']")
There are even 3 elements with id="_loginButton" on the page, and only one is visible - the one located inside the login form, you can get it by a CSS selector:
By.cssSelector("form#_loginForm div#_loginButton")
There are 3 occurrences of id="_loginButton".
Used the id="_loginButton" under class="signIn" by cssSelector to get the exact button in the page.
By.cssSelector("div.signIn div#_loginButton")
Webdriver may throw an ElementNotVisible exception in-case there are multiple elements with the same locator and if Webdriver has already operated upon one of the element matching the locator.
In such scenarios you can first get the size of the element using
int var_ele_size= driver.findElements(By.xpath("locator")).size();
and then take the first element from the list and click on the element.
driver.findElements(By.xpath("locator")).get(var_ele_size-1).click();
public static void Listget (WebDriver driver) throws Exception
{
Thread.sleep(5000);
UtilityMethod.getAppLocaters(driver, "closeicon").click();
Actions action = new Actions(driver);
WebElement we = driver.findElement(By.xpath("//li[#class='parent dropdown aligned-left']"));
Thread.sleep(5000);
action.moveToElement(we).build().perform();
List<WebElement>links = driver.findElements(By.xpath("//span[#class='menu-title']"));
int total_count = links.size();
System.out.println("Total size :=" +total_count);
for(int i=0;i<total_count;i++)
{
WebElement element = links.get(i);
String text = element.getAttribute("innerHTML");
System.out.println("linksnameis:=" +text);
try{
File src = new File("D:ReadFile.xlsx");
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb=new XSSFWorkbook(fis);
XSSFSheet sh = wb.getSheetAt(0);
sh.createRow(i).createCell(1).setCellValue(text);
FileOutputStream fos = new FileOutputStream(new File("D:/ReadFile.xlsx"));
wb.write(fos);
fos.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
}
Make sure your window on the remote server is big enough so the elements are not hidden because of space constraints ..
This worked for me: (I use c#)
driver.Manage().Window.Size = new System.Drawing.Size(1928, 1060);
You could try:
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("your locator value")));
Or
wait.until(ExpectedConditions.ElementIsVisible(By.xpath("your locator value")));