how to test data table in selenium - selenium

I want to test a data in html table.and verify it with database which contains the staff information. Below is the code. now i am stuck for creating assert, how to collect the rows or list of list of the table values
#Test
public void TestingReport()
{
driver.findElement(By.xpath(".//*[#id='content']/h2[2]/a")).click(); // click on admin
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.xpath("//*[#id='content']/h2[2]/a")).click(); // click on staff member
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// ArrayList<ArrayList> ActualReport= new ArrayList<ArrayList>();
List<WebElement> tablerow = driver.findElements(By.xpath("//table//tr"));
ArrayList <String> cellsStr = new ArrayList<>();
ArrayList<List> table = new ArrayList<>();
List<WebElement> cells= null ;
// System.out.println(tablerow.size());
for(int i=1;i<tablerow.size();i++) {
cells = driver.findElements(By.xpath("//tr["+i+"]//td"));
// table.add(cells);
for(int j=4;j<cells.size();j++)
{
System.out.println(cells.get(j).getText());
cellsStr.add(cells.get(j).getText());
}
System.out.println(cellsStr);
table.add(cellsStr);
System.out.println(table);
System.out.println(cellsStr);
}
System.out.println(table);
}
Here i am trying to get an Arraylist of sting in to a string, but before the next iteration i am clearing the Arraylist of string, but it is making the List of array list also empty.

Below helps to get the data from list of list of values.
List<WebElement> tablerow = driver.findElements(By.xpath("//table//tr"));
for(int i=1;i<tablerow.size();i++)
{
List<WebElement> cells= tablerow.get(i).findElements(By.tagName("td"));
for(int j=4;j<cells.size();j++){
List<WebElement> cellSubRow= cells.get(i).findElements(By.tagName("td"));
System.out.println(cellSubRow.get(j).getText());}}

Related

Why my selenium function say no Element found

Why if i use same code of affordabilityErrorVerify() in mortgageCalculator() function its working fine but when i use that code in affordabilityErrorVerify() [ same as i posted here ] it says : --> org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"#ifrm_13536"}
its weird for me can someone help me how i can make it work
public class test1 extends base {
public WebDriver driver;
public static Logger log =LogManager.getLogger(base.class.getName());
#BeforeTest
public void initialize() throws IOException {
driver = initializeDriver(); // initialize the browser driver based on data.properties file browser value
}
#Test(dataProvider = "dataDriven")
public void mortgageCalculator(String amount, String year, String Frequency, String type, String product,
String term, String rate) throws IOException, InterruptedException {
driver.get(prop.getProperty("url")); // read the data.properties file for get the value of url
driver.manage().window().maximize();
LandingPage l = new LandingPage(driver); // created object for Landing page to access page element
Actions actions = new Actions(driver);
WebElement mainMenu = l.menuBar();
actions.moveToElement(mainMenu);
WebElement subMenu = l.clickLink();
actions.moveToElement(subMenu);
actions.click().build().perform();
// Explicit wait because calculator is in frame and it loads after some time
// so wait until frame is visible
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(#class,'col-12 col-md-9 side-content')]")));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,500)");
// switch to frame elements
driver.switchTo().frame(l.switchToFrame());
Thread.sleep(3000);
l.productTabClick().click(); // click on product tab
Thread.sleep(3000);
WebElement money = l.mortgageAmount();
money.click();
money.sendKeys(Keys.CONTROL + "a");
money.sendKeys(Keys.DELETE);
money.sendKeys(amount);
WebElement period = l.mortgageYear();
period.click();
period.sendKeys(Keys.CONTROL + "a");
period.sendKeys(Keys.DELETE);
period.sendKeys(year);
Select s = new Select(l.paymentFrequency());
s.selectByValue(Frequency);
// if data provider send Fixed it will click on fixed radio button otherwise click on variable
if (type == "Fixed") {
l.paymentType().click();
} else {
l.paymentType().click();
}
Select ss = new Select(l.paymentProduct());
ss.selectByValue(product);
Thread.sleep(3000);
driver.switchTo().defaultContent();
js.executeScript("window.scrollBy(0,300)");
driver.switchTo().frame(l.switchToFrame());
Thread.sleep(3000);
WebElement inputOwnRateTerm = l.paymentTerm();
inputOwnRateTerm.click();
inputOwnRateTerm.sendKeys(Keys.CONTROL + "a");
inputOwnRateTerm.sendKeys(Keys.DELETE);
l.paymentTerm().sendKeys(term);
WebElement inputOwnRateValue = l.paymentRate();
inputOwnRateValue.click();
inputOwnRateValue.sendKeys(Keys.CONTROL + "a");
inputOwnRateValue.sendKeys(Keys.DELETE);
l.paymentRate().sendKeys(rate);
inputOwnRateValue.sendKeys(Keys.ENTER);
Thread.sleep(3000);
String actualPayment = l.monthlyPayment().getText();
String actualIOT = l.interestOverTerm().getText();
String actualInterestOverTerm = actualIOT.substring(0, actualIOT.length()-1);
//double actualInterestOverTerm = Math.round(actualIOT)* 10.0) / 10.0;
//System.out.print(actualPayment); // uncomment to see what Mortgage Payment amount function is returning for given data
//System.out.print(actualInterestOverTerm);
//System.out.print(actualIOT);
String totalAmount = amount;
int arg1 = Integer.parseInt(totalAmount);
String mortgageRate = rate;
double arg2 = Double.parseDouble(mortgageRate);
String totalYear = year;
int arg3 = Integer.parseInt(totalYear);
// to find out total Interest over term months based on year
String iot = term;
int iot1 = Integer.parseInt(iot);
int arg4 = iot1 * 12;
// Pass all 4 argument into mortgage calculator to assert actual and expected result
calculator c = new calculator();
double[] expected = c.mortgageCalculator(arg1, arg2, arg3, arg4);
//System.out.println("Mortgage Payment :" + expected[0]); // giving back Mortgage Payment amount from custom function
//System.out.println("Interest over term :" + expected[1]); // giving back Interest over term amount from custom function
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance(); // converting numbers into money format [number format]
String act = defaultFormat.format(expected[1]);
String expectedInterestOverTerm = act.substring(0, act.length()-1);
//***********************
// ActualPayment = Getting value from https://www.coastcapitalsavings.com/calculators/mortgage-calculator
// Expected[0] = Getting value from calculator() function which is mortgageCalculator logic file
//***********************
Assert.assertEquals(actualPayment,defaultFormat.format(expected[0])); // Assertion to find out both values are same
Assert.assertEquals(actualInterestOverTerm,expectedInterestOverTerm); // Assertion to find out both values are same
log.info("*************Expected****************");
log.info("Mortgage Payment :" + expected[0]);
log.info("Interest Over Term :" + expectedInterestOverTerm);
log.info("**************Actual*****************");
log.info("Mortgage Payment :" + actualPayment);
log.info("Interest Over Term :" + actualInterestOverTerm);
log.info("_______________________________________");
}
#Test
public void affordabilityErrorVerify() throws InterruptedException
{
LandingPage l = new LandingPage(driver); // created object for Landing page to access page element
JavascriptExecutor js = (JavascriptExecutor) driver;
Thread.sleep(3000);
driver.switchTo().defaultContent();
js.executeScript("window.scrollBy(0,-500)");
Thread.sleep(3000);
driver.switchTo().frame(l.switchToFrame());
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(#class,'col-12 col-md-9 side-content')]")));
Thread.sleep(3000);
l.affordabilityTabClick().click(); // click on affordability tab
Thread.sleep(3000);
driver.findElement(By.cssSelector("slider-control:nth-child(3) > #slider-container #name")).click();
driver.findElement(By.cssSelector("slider-control:nth-child(3) > #slider-container #name")).sendKeys("10000");
driver.findElement(By.cssSelector("slider-control:nth-child(3) > #slider-container #name")).sendKeys(Keys.ENTER);
}
By looking at your code, I have a probable solution to your problem.
There is no priority defined for tests. So in TestNG, if priority is not defined, the test will get executed in alphabetical order. In this case, affordabilityErrorVerify() test will execute first and then mortgageCalculator().
If I observe affordabilityErrorVerify(), there is no method to open URL like driver.get(url) so no page will get open and it will cause NoSuchElementException
A possible answer can be assigned priority to tests
#Test (priority=1, dataProvider = "dataDriven")
public void mortgageCalculator(String amount, String year, String Frequency, String type, String product,
String term, String rate) throws IOException, InterruptedException {
//code
}
#Test (priority=2)
public void affordabilityErrorVerify() throws InterruptedException
{
//code
}
In this as well you have to make sure actions on second test are continuing on same page where test1 ends.
Modify your tests and actions considering flow of test and it will work
Happy coding~

Not able to write output in the excel using selenium code

public class AustriaRegro {
public String Result;
WebDriver driver;
WebDriverWait wait;
Sheet s;
WritableSheet ws;
WritableWorkbook wc;
Workbook w;
#Test
public void TestSetup() throws IOException, BiffException, RowsExceededException, WriteException{
System.setProperty("webdriver.chrome.driver","C:\\Users\\yirsh\\Desktop\\Selenium\\chromedriver_win32\\chromedriver.exe");
driver=new ChromeDriver();
FileInputStream fi = new FileInputStream("C:\\Users\\yirsh\\Desktop\\UAT WEBSHOP.xls");
w = Workbook.getWorkbook(fi);
s = w.getSheet("Regro");
FileOutputStream fo = new FileOutputStream("C:\\Users\\yirsh\\Desktop\\UATWEBSHOPResult.xls");
wc =Workbook.createWorkbook(fo);
ws = wc.createSheet("Query_data", 0);
Sheet sheets = w.getSheet("Query_data");
String inputdata[] [] = new String[s.getRows()][s.getColumns()];
for (int i=0;i<s.getRows();i++)
{
for(int k=0;k< s.getColumns();k++)
{
inputdata[i][k] = s.getCell(k,i).getContents();
Label l = new Label(k,i , inputdata[i][k]);
Label la = new Label(4,0,"Results");
ws.addCell(l);
ws.addCell(la);
}
}
for(int row=1; row <= s.getRows() ; row++){
driver.manage().deleteAllCookies();
wait = new WebDriverWait(driver,30);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://path/");
driver.manage().window().maximize();
String username = s.getCell(2,row).getContents();
System.out.println("***********************************");
System.out.println("Username: "+username);
driver.findElement(By.id("j_username_leftAside")).sendKeys(username);
String password= s.getCell(3,row).getContents();
System.out.println("Password: "+password);
driver.findElement(By.id("j_password_leftAside")).sendKeys(password);
driver.findElement(By.xpath("/html[#class=' js opacity generatedcontent pointerevents']/body[#class='page-homepage pageType-ContentPage template-pages-layout-RexelHomePageLayout pageLabel-homepage language-de ']/div[#id='page']/div[#id='content']/div[#id='content']/div[#class='content-top-inner']/div[#id='content-inner']/div[#class='mid-wrapper'][1]/div[#class='yCmsContentSlot']/div[#class='login clear']/form[#id='loginForm']/div[#class='left sign-in']/button[#class='Sign-in rx-btn mb0']")).click();
try{
if((driver.findElement(By.xpath(".//*[#id='globalMessages']/div"))).isDisplayed()){
System.out.println("Login Failed");
Result="Failed";
String Error=driver.findElement(By.xpath(".//*[#id='globalMessages']/div")).getText();
System.out.println("The Error mesaage is :"+Error);
System.out.println("***********************************************************************************************************");
}
}
catch (Exception e){
System.out.println("Login Sucessfull");
Result="Pass";
System.out.println("***********************************");
driver.findElement(By.xpath(".//*[#id='content-inner']/div[1]/div/div[2]/div[3]/div/div/ul/li[9]/a")).click();
}
Label lb = new Label(4,1,Result);
ws.addCell(lb);
}
driver.close();
}
}
I am writing a code to fetch data from an excel sheet and run selenium tests on it and write the output in a different excel file. Result Excel has been created but data is not inserted.Need to correct the code so that it can insert the results.Only saving the result in excel is pending remaining all working fine as expected.
You'll need to write to file. I believe you can do so by calling WritableWorkbook.write(). Remember to close the files afterward.
...
...
Label lb = new Label(4,1,Result);
ws.addCell(lb);
}
wc.write();
wc.close();
w.close();
driver.close();
See the documentation here. The write function can throw an IOException, so you'll have to handle that at some point - I see you're passing that exception up the stack, that's fine.

Get dropdown values using actions class

After moving to the value which is present in dropdown, i want to get it using actions class. Below is the code i have written. i am trying to print the dropdown values. HTML tag for dropdown is input(for select i have code). Please help me
public static void caseSearch()
{
try
{
Actions a=new Actions(driver);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
logger.info("clicking on cases tab :: ");
driver.findElement(By.xpath(loader.getProperty(Constants.CaseTab))).click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
WebElement ele=driver.findElement(By.xpath(loader.getProperty(Constants.CaseSearch)));
ele.click();
for(int i=0;i<=20;i++)
{
//i want to print the first value of dropdown in console
a.sendKeys(Keys.DOWN,Keys.DOWN,Keys.DOWN).build().perform();
String value=ele.getText();
System.out.println("value is = "+value);
a.sendKeys(Keys.DOWN,Keys.DOWN).build().perform();
Thread.sleep(3000);
a.sendKeys(Keys.ENTER).build().perform();
}
}
catch(Exception e)
{
logger.info("case search method is not executed :: " +e);
}
}
I think you forgot to get the value from the dropdown box.
You need to use the Select Class to get it.
Actions key = new Actions(browser);
WebElement dropdownElement = this.browser.findElement(By.xpath("YOUR DROPDOWN ELEMENT"));
Select dropOptions = new Select(dropdownElement);
int elements = dropOptions.getOptions().size();
for (int i = 0; i < elements; i++) {
dropdownElement.click();
if (i > 0) {
Thread.sleep(1000L);
key.sendKeys(Keys.DOWN).build().perform();
Thread.sleep(1000L);
key.sendKeys(Keys.ENTER).build().perform();
}
else {
Thread.sleep(1000L);
ActionPerformers.sendActionKey(browser, Keys.ENTER);
}
System.out.println("ELEMENT " + i + " -> " + dropOptions.getFirstSelectedOption().getText()); //Here you will get the selected Value...
}
This is only an exemple, I hope it suits you.

How to sort a list

I need to check if the list is in alphabetical order. SysPrint seems like that the list is in alphabetical order, but assertion throws an error that the list is NOT in alphabetical order. Any help is greatly appreciated!
java.lang.AssertionError: Advertiser is not in alphabetical order. expected [true] but found [false]".
My Script:
try {
WebDriverWait wait = new WebDriverWait(driver, 30);
List<String> displayed = new ArrayList<String>();
List<String> sorted = new ArrayList<String>();
List<WebElement> verifyAdvertiser = wait
.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By
.xpath(".//*[#id='basic']/div[4]/table/tbody[2]/tr")));
System.out.println("NUMBER OF ROWS IN THIS TABLE = "
+ verifyAdvertiser.size());
for (WebElement element : verifyAdvertiser) {
System.out.println("" + element.getText());
displayed.add(element.getText());
sorted.add(element.getText());
}
Collections.sort(sorted);
log.info(sorted);
if (!displayed.equals(sorted)) {
final String failedMsg = "Advertiser is not in alphabetical order.";
log.error(failedMsg, null);
boolean passed = false;
Assert.assertTrue(passed, failedMsg);
}
} catch (Exception e) {
final String failedMsg = "Failed trying to check agency names in alphabetical order.";
log.error(failedMsg, e);
boolean passed = false;
Assert.assertTrue(passed, failedMsg);
}

Selenium WebDriver generates StaleElementReferenceExeption on getText() on table elements

The current environment:
Selenium Server version 2.37.0
RemoteWebDriver running on Firefox
no Ajax / asynchronously loaded content
My tests are attempting to validate the content of each cell of an HTML table. Before accessing any table element an explicit wait verifies that the <tbody> element exists
ExpectedCondition<WebElement> recruitTableIsPresent = ExpectedConditions.presenceOfElementLocated(By.id("newRecruitFieldAgentWidget:newRecruitDataTable_data"));
new WebDriverWait(driver, 5).until(recruitTableIsPresent);
Once the table is verified to exist, data is pulled out by row and column
private Stats[] parseStats() {
String xpath = "//tbody[#id='regionalFieldAgentWidget:regionalDataTable_data']/tr[%d]/td[%d]";
Stats[] stats = new Stats[3];
for (int i = 0; i < stats.length; i++) {
String inProgresOrders = cellContent(xpath, i, 1);
String maxCapacity = cellContent(xpath, i, 2);
String allocationRatio = cellContent(xpath, i, 3);
Stats[i] = new Stats(inProgressORders, maxCapacity, allocationRatio);
}
return stats;
}
private String cellContent(String xpathTemplate, int row, int cell) {
String xpath = String.format(xpathTemplate, row + 1, cell + 1);
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath)));
WebElement elementByXPath = driver.findElementByXPath(xpath);
return elementByXPath.getText();
}
I don't see any race conditions, since the table content is populated with the page, and not in an asynchronous call. Additionally, I have seen other answers that suggest invoking findElement() via the driver instance will refresh the cache. Lastly, the explicit wait before accessing the element should ensure that the <TD> tag is present.
What could be causing the getText() method return the following exception:
org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
It's worthwhile to note that the failure is intermittent. Some executions fail while other passes through the same code pass. The table cell causing the failure are also not consistent.
There is a solution to this using Html-Agility-Pack.
This will work only if you want to read the data from that page.
This goes likes this
//Convert the pageContent into documentNode.
void _getHtmlNode(IWebDriver driver){
var htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(driver.PageSource);
return htmlDocument.DocumentNode;
}
private Stats[] parseStats(){
String xpath = "//tbody[#id='regionalFieldAgentWidget:regionalDataTable_data']/tr[%d]/td[%d]";
Stats[] stats = new Stats[3];
for (int i = 0; i < stats.Length; i++) {
String inProgresOrders = cellContent(xpath, i, 1);
String maxCapacity = cellContent(xpath, i, 2);
String allocationRatio = cellContent(xpath, i, 3);
Stats[i] = new Stats(inProgressORders, maxCapacity, allocationRatio);
}
return stats;
}
private String cellContent(String xpathTemplate, int row, int cell) {
String xpath = String.format(xpathTemplate, row + 1, cell + 1);
new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath)));
var documentNode = _getHtmlNode(driver);
var elementByXPath = documentNode.SelectSingleNode(xpath);
return elementByXPath.InnerText;
}
now read any data.
Some tips for using htmlNode.
1. Similar to driver.FindElement: document.SelectSingleNode
2. Similar to driver.FindElements: document.SelectNodes
3. Similar to driver.Text: document.InnerText.
For more search regarding HtmlNode.
Turns out there was a race condition as I've already mentioned. Since jQuery is available via PrimeFaces there is a very handy solution mentioned in a few other posts. I implemented the following method to wait for any asynchronous requests to return before parsing page elements
public static void waitForPageLoad(JavascriptExecutor jsContext) {
while (getActiveConnections(jsContext) > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
}
private static long getActiveConnections(JavascriptExecutor jsContext) {
return (Long) jsContext.executeScript("return (window.jQuery || { active : 0 }).active");
}
Each built in driver implementation implements the JavascriptExecutor interface, so the calling code is very straightforward:
WebDriver driver = new FirefoxDriver();
waitForPageLoad((JavascriptExecutor) driver);