selenium dynamic growing table - java

I have some troubles to handle dynamic growing table with selenium.
To sum up quickly, on my web app I have a table with 30 items but it only displays the twenty first items and we have to scroll down to display the rest.
And I don't know how to get the 26th (for example) items without scrolling down.
My HTML:
<table id="tableID" tabindex="0" aria-multiselectable="true" role="grid">
<thead>
<tbody id="tableID-tblBody">
<tr id="item1" role="row" tabindex="-1">
<tr id="item2" role="row" tabindex="-1">
[... 17 more]
<tr id="item20" role="row" tabindex="-1">
</tbody>
</table>
After scrolling:
<table id="tableID" tabindex="0" aria-multiselectable="true" role="grid">
<thead>
<tbody id="tableID-tblBody">
<tr id="item1" role="row" tabindex="-1">
<tr id="item2" role="row" tabindex="-1">
[... 27 more]
<tr id="item30" role="row" tabindex="-1">
</tbody>
</table>
If someone could help me it would be great ^^
Thanks!

I would scroll into view of the last row in the table (if necessary multiple times until you get the desired row count). For this I'd use scrollIntoView() via executeScript():
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("arguments[0].scrollIntoView();", element);
where element:
WebElement element = driver.findElements(By.xpath("//table[#id = 'tableID']//tr[last()]")).

You cant get that item without scrolling down (to scroll down use #alecxe solution), because the element you want to choose is not even in the html at the time you search for it.
After the scroll you should be able to find it easily by id.

I think you are trying to compare values
Expected Value V/s Actual Value.
To do this I would request you to take all elements/object under this table : tableID-tblBody and search for ID of 26 and take value.
Here is my code that I used to perform similar task.
WebDriverWait wait = new WebDriverWait(driver, timeout);
List<WebElement> totalrow = wait.until(ExpectedConditions
.presenceOfAllElementsLocatedBy(By.Id("tableID-tblBody"));
for (int i = 0; i <= totalrow.size(); i++) {
String xPath ="" //"XPATH OF 26 ITEM";
try {
WebElement element = ExpectedBehaviors
.expectPresenceofElementBy(driver, By.xpath(xPath),
getAlertTimeout());
if (element.getText().trim().equals("EXPECTED VALUE")) {
//"PERFORM YOUR ACTION"
break;
}
} catch (Exception e) {
//"You can add your exception and error message
}
}

Related

Selenium, Java- finding table by class (without ID)

I have something like this:
<table class="table">
<thead>
<tr>
<th>Role</th>
<th>Description</th>
<th>Access</th>
<th>Grant</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="role in roles">
<td>{{role.role_name}}</td>
<td>{{role.role_description}}</td>
<td><input type="checkbox" ng-model="role.allow_access" ng-change="updateAllow(role)" ng-disabled="!(role.grantor_allow_grant == 'Y' || haveAllAdminRoles)" ng-true-value="'Y'" ng-false-value="'N'"></td>
<td><input type="checkbox" ng-model="role.allow_grant" ng-change="updateAllow(role)" ng-disabled="!(role.grantor_allow_grant == 'Y' || haveAllAdminRoles)" ng-true-value="'Y'" ng-false-value="'N'"></td>
</tr>
</tbody>
</table>
How I can find this table using WebDriver or WebConnector ? I tried sth like this:
WebElement table = driver.findElement(By.className("table"));
and it doesn't work, I received error:
org.openqa.selenium.NoSuchElementException: Unable to locate element:
Thanks for any help.
That might be due to timing issue. You can use explicit wait to wait for the table to load or to be visible
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement table = wait.until(ExpectedConditions.presenceOfElementLocated(By.className("table")));
// or
WebElement table = wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("table")));
May be when you are going to finding table, it could not be visible on the page due slow internet or other reason. To make sure table visible on the page try to find using WebDriverWait to wait until table visible as below :-
WebDriverwait wait = new WebDriverwait(driver, 10);
WebElement table = wait.until(Expectedconditions.visibilityOfElementLocated(By.className("table")));
Hope it helps..:)

HREF + TEXT with Jsoup

I've the following HTML Page:
</div><div id="page_content_list01" class="grid_12">
<h2><strong class="floatleft">TEXT1</strong></h2><br>
<table>
<tbody>
<tr>
<th class="no_width">
<p class="floatleft">Attachments:</p>
</th>
<td class="link_azure">
<a target="_blank" href="http://www.example.com">TEXT2</a><br/>
</td>
</tr>
</tbody>
</table><h2><strong class="floatleft">TEXT3</strong></h2><br>
<table>
<tbody>
<tr>
<th class="no_width">
<p class="floatleft">Atachments:</p>
</th>
<td class="link_azure">
<a target="_blank" href="http://www.example2.com">TEXT4</a><br/>
</td>
</tr>
</tbody>
</table><h2><strong class="floatleft">TEXT5</strong></h2><br>
<table>
<tbody>
<tr>
Actually I'm doing:
Elements rows = document.select("div#page_content_list01");
Now I to select "TEXT" and link. I wanna to make clickable link, so I'm using:
for (Element eleme : rows) {
Elements elements = eleme.select("a");
for (Element elem : elementi) {
String url = elem.attr("href");
String title = elem.text();
}
}
and I'm getting:
url = "http://www.example.com";
title = "TEXT2";
and it's ok, but in this way I can't read "TEXT1" and "TEXT3".
Can someone help me please?
I think you need to work on the selecors. First, your primary selector
Elements rows = document.select("div#page_content_list01");
will return with a list of ONE element only, since you actually select the div, not the tables or table rows. I would instead do this to get all relevant info:
Elements tables = document.select("div#page_content_list01>table");
for (Element table : tables){
Element h2 = table.previousElementSibling();
String titleStr = h2.text();
Element a = table.select("a").first();
String linkStr = a.attr("href");
}
Note that the Text in the h2 elements is on the same level as the table, not inside a common div. This is why I use the previous sibling notation. Also note that I wrote this out of my head and it is untested. You should get the idea though.

How to locate links in a calendar table using webdriver and java?

I'm learning to work with Maven, Java, testng and webdriver by doing a self training course. I been doing great with all exercises until I got to the last one, I honestly don't know how to solve it. Let me give you some context:
Exercise description: Open the site homepage and using the calendar(html calendar in a wordpress site), check how many days of
the current month contain posts, then access the first day which has
post and print the titles of the posts in the console.
When any day in the calendar has posts, instead of showing the day in
plain text, the site shows the day number as a link that once clicked
opens the lists of posts in the main page.
This is a screen capture of how this site looks when I click on the day which has posts, in this case October 10th 2013: http://i.stack.imgur.com/wGRO2.jpg
Like I said the site is a wordpress site (unfortunately can only be accessed through VPN so I can't share it), and I need to use the calendar widget which is a table. I was able to go over each row and column of the table and print each column's text.
But how do I find if any of those days have a link in it and then having located that element how can I access it and print it's content (is this case they want me to print the titles of all posts created under that date)?
This is the code I'm using to go over the entire table and print the content:
//Test Case 6
#Test (timeOut=20000)
public void TestCalendar(){
HomePage homePage = PageFactory.initElements(driver, HomePage.class);
homePage.Go(driver);
WebElement table = homePage.ReturnCalendarElement();
//Actual Month has no posts, so we select previous one which has 2 posts
homePage.ClickPreviousMonth();
//We Get All rows of the calendar then we get all columns and its data
List<WebElement> rows = table.findElements(By.tagName("tr"));
for (WebElement row: rows) {
List<WebElement> cols= row.findElements(By.tagName("td"));
for (WebElement col: cols){
System.out.print(col.getText() + "\t");
}
}
}
I'm adding the HTML code of that page in case it helps you to provide some answers:
Follow this link to open a Public Gist with the HTML code of the page: https://gist.github.com/anonymous/599cd722b5c906808528
The following is the HTML code for the Table I'm testing:
<aside id="calendar-2" class="widget widget_calendar"><h3 class="widget-title">Posts by date:</h3><div id="calendar_wrap"><table id="wp-calendar">
<caption>October 2013</caption>
<thead>
<tr>
<th scope="col" title="Monday">M</th>
<th scope="col" title="Tuesday">T</th>
<th scope="col" title="Wednesday">W</th>
<th scope="col" title="Thursday">T</th>
<th scope="col" title="Friday">F</th>
<th scope="col" title="Saturday">S</th>
<th scope="col" title="Sunday">S</th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="3" id="prev" class="pad"> </td>
<td class="pad"> </td>
<td colspan="3" id="next" class="pad"> </td>
</tr>
</tfoot>
<tbody>
<tr>
<td colspan="1" class="pad"> </td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
<td>13</td>
</tr>
<tr>
<td>14</td>
<td>15</td>
<td>16</td>
<td>17</td>
<td>18</td>
<td>19</td>
<td>20</td>
</tr>
<tr>
<td>21</td>
<td>22</td>
<td>23</td>
<td>24</td>
<td>25</td>
<td>26</td>
<td>27</td>
</tr>
<tr>
<td>28</td>
<td>29</td>
<td>30</td>
<td>31</td>
<td class="pad" colspan="3"> </td>
</tr>
</tbody>
</table></div></aside>
This is the last problem I need to solve to end with this training, so any help and orientation will be highly appreciated.
Use a better CSS query to get the links of the calendar.
It would be something like:
td a
Elements TD with a link A inside.
Not much help without the HTML code of the page.
I ended up finding a solution, while i'm sure there should be a better way to do this. But this worked for me & might help someone else somehow:
// Test Case 6
#Test(timeOut = 40000)
public void TestCalendar() {
HomePage homePage = PageFactory.initElements(driver, HomePage.class);
CalendarPage calendarPage = PageFactory.initElements(driver,
CalendarPage.class);
homePage.Go(driver); //this just navigates to the page
homePage.ReturnPreviousMonth().click();
//returns the calendar element mapped in the page
WebElement table = homePage.ReturnCalendarElement();
WebElement dayWithPost = calendarPage.GetFirstDayWithPosts(driver,
table);
Assert.assertNotNull(dayWithPost);
System.out.println("We'll be working with the following day: " + dayWithPost.getText());
dayWithPost.click();
List<WebElement> articles = driver.findElements(By
.className("entry-title"));
for (WebElement article : articles) {
System.out.println("Retrieved Post's Title: [ "
+ article.findElement(By.tagName("a")).getText() + " ]");
}
public class CalendarPage {
public List<WebElement> ReturnArticlesOnPage(WebDriver driver) {
List<WebElement> articles = driver.findElements(By.tagName("article"));
return articles;
}
public WebElement GetFirstDayWithPosts(WebDriver driver, WebElement table) {
List<WebElement> rows = table.findElements(By.tagName("tr"));
for (WebElement row : rows) {
List<WebElement> cols = row.findElements(By.tagName("td"));
for (WebElement col : cols) {
try {
if (col.findElement(By.tagName("a")).getAttribute("href") != null ){
System.out.println("Day: " + col.getText()+ " has posts and was returned.");
return col;
}
}
catch (NoSuchElementException e){
//System.out.println("Day: " + col.getText()+ " has no posts.");
}
}
}
return null;
}
}

Locating data in a complex table in Selenium Webdriver

I am currently trying to drill down on a user in a table full of users using Selenium webdriver, I have worked out how to iterate through the table but I'm having trouble actually selecting the person I want.
Here is the HTML (modified with X's due to it not being my data)
<table id="XXXXXXXXX_list" cellspacing="0" cellpadding="0" style=" border:0px black solid;WIDTH:100%;">
<tbody>
<tr cellspacing="0" style="height: 16px;">
<tr>
<tr onclick="widgetListView_onClick('XXXX_list',1,this,event)">
<tr onclick="widgetListView_onClick('XXXX_list',2,this,event)">
<tr onclick="widgetListView_onClick('XXXX_list',3,this,event)">
<tr onclick="widgetListView_onClick('XXXX_list',4,this,event)">
<tr onclick="widgetListView_onClick('XXXX_list',5,this,event)">
<tr onclick="widgetListView_onClick('XXXX_list',6,this,event)">
<tr onclick="widgetListView_onClick('XXXX_list',7,this,event)">
<td class="listView_default_dataStyle" nowrap="" style="font-size:12px ;
font-family: sans-serif ;color: black ;background: #FFFFFF "
ondblclick="XXXXListView_onDblClick('XXXXX_list',17, event)">NAME</td>
<td class="listView_default_dataStyle" nowrap="" style="font-size:12px ;font-family: sans-serif;
color: black ;background: #FFFFFF " ondblclick="XXXXX_onDblClick('XXXX_list',17, event)"> </td>
</tr>
Here is the code I am writing to try and find the user going by NAME in the table.
WebElement table = driver.findElement(By.id("table_list"));
// Now get all the TR elements from the table
List<WebElement> allRows = table.findElements(By.tagName("tr"));
// And iterate over them, getting the cells
for (WebElement row : allRows) {
List<WebElement> cells = row.findElements(By.tagName("td"));
for (WebElement cell : cells) {
List<WebElement> Names = cell.findElements(By.xpath("//td[text()='NAME']"));
System.out.println(Names);
This just prints thousands of [] (the table is huge in the real application).
Essentially what I need is to stop when I find the correct name and create a web element out of that table row. Which I can then click and drill down on.
Sorry if any of this is a bit vague,
Well if each name in the table is unique, you don't need to complicate things so much. Just search for element with text matching your 'Name' then select the row accordingly. Look at the code below:
WebElement name = driver.findElement(By.xpath("//table[#id='XXXXXXXXX_list']//td[contains(text(),'NAME')]"));//Select td with text NAME in table with id XXXXXXXXX_list
WebElement rowWithName = name.findElement(By.xpath("./.."));//Select the parent node, i.e., tr, of the td with text NAME
/*
* Look into that row for other element or perform any action on the row.
*/
If the names are not unique, i.e., same name exists twice at similar node, 1st instance will be picked each time. In that case we will have to try things differently, i.e., we will have to index the xpath for correct instance of matching name. Do ask if you have any further doubts :)
This will help you out.
try{
ArrayList<WebElement> cells = (ArrayList<WebElement>) driver.findElements(By.tagName("td"));
log4j.info("Value = "+input_type+" is stored in array from Webpage for "+keyword+" ");
for(WebElement type : cells)
{
if(type.getAttribute("name").equals("your correct name here")) {
type.sendKeys("ABC");
}
}
return true;
}catch(Throwable e){
return false;
}
You need to use Array list like this and you can compare your Name in which you wanna fill value Or wanna do any operation like getText(), click() etc.
Enjoy!

dynamic table data retrieve - selenium webdriver

<table id="tblListViewHeader" class="adminlist" cellspacing="1" cellpadding="0" style="table-layout: fixed; width: 1003px;">
<tbody>
</table>
</td>
</tr>
<tr>
<td>
<div id="divListView" style="width: 100%; height: 300px; overflow: auto; display: block;">
<table id="tblListView" class="adminlist" cellspacing="1" cellpadding="0" style="table-layout: fixed; width: 100%;">
<tbody data-bind="template: { name: 'ActiveGradeTemplate', foreach: ActiveGrade }">
<tr class="row0">
<td data-bind="text:$index()+1" style="width: 5%;">1</td>
<td data-bind="text: GradeName" style="width: 20%;">Vantage Point</td>
<td align="right" data-bind="text: DisplayCreatedDate" style="width: 10%;">27 Mar 2013</td>
<td align="right" data-bind="text: CreatedByUser" style="width: 10%;">Name</td>
<td align="right" data-bind="text: DisplayModifiedDate" style="width: 10%;">27 Mar 2013</td>
<td align="right" data-bind="text: ModifiedByUser" style="width: 10%;">Name</td>
<td align="center" data-bind="text: Status" style="width: 5%;">Active</td>
<td align="center" style="width: 10%;">
<a id="lnkEdit_7" data-bind="click: $root.lnkEdit, attr:{'id':'lnkEdit_' + GradeID}" href="#">Edit</a>
<span id="spanEdit_7" data-bind="attr:{'id':'spanEdit_' + GradeID}"></span>
</td>
</tr>
<tr class="row0">
<td data-bind="text:$index()+1" style="width: 5%;">2</td>
<td data-bind="text: GradeName" style="width: 20%;">test grade</td>
<td align="right" data-bind="text: DisplayCreatedDate" style="width: 10%;">Yesterday</td>
<td align="right" data-bind="text: CreatedByUser" style="width: 10%;">Name</td>
<td align="right" data-bind="text: DisplayModifiedDate" style="width: 10%;">Yesterday</td>
<td align="right" data-bind="text: ModifiedByUser" style="width: 10%;">Name</td>
<td align="center" data-bind="text: Status" style="width: 5%;">Active</td>
<td align="center" style="width: 10%;">
<a id="lnkEdit_11" data-bind="click: $root.lnkEdit, attr:{'id':'lnkEdit_' + GradeID}" href="#">Edit</a>
<span id="spanEdit_11" data-bind="attr:{'id':'spanEdit_' + GradeID}"></span>
</td>
</tr>
How can I retrieve the td values for each and every row, this is for Dynamic generation. All the tr class names are the same: <tr class="row0">. How do I retreive the table data for the above formatted table?
Try below code, this will print all cells data,
// Grab the table
WebElement table = driver.findElement(By.id("divListView"));
// Now get all the TR elements from the table
List<WebElement> allRows = table.findElements(By.tagName("tr"));
// And iterate over them, getting the cells
for (WebElement row : allRows) {
List<WebElement> cells = row.findElements(By.tagName("td"));
// Print the contents of each cell
for (WebElement cell : cells) {
System.out.println(cell.getText());
}
}
// Grab the table
WebElement table = driver.findElement(By.id("table-6"));
//Get number of rows in table
int numOfRow = table.findElements(By.tagName("tr")).size();
//Get number of columns In table.
int numOfCol = driver.findElements(By.xpath("//*[#id='table-6']/tbody/tr[1]/td")).size();
//divided Xpath In three parts to pass Row_count and Col_count values.
String first_part = "//*[#id='table-6']/tbody/tr[";
String second_part = "]/td[";
String third_part = "]";
//take the second column values
int j=2;
//List to store the second column
List<String> secondColumnList=new ArrayList<String>();
//Loop through the rows and get the second column and put it in a list
for (int i=1; i<=numOfRow; i++){
//Prepared final xpath of specific cell as per values of i and j.
String final_xpath = first_part+i+second_part+j+third_part;
//Will retrieve value from located cell and print It.
String test_name = driver.findElement(By.xpath(final_xpath)).getText();
secondColumnList.add(test_name);
System.out.println(test_name);
}
Dynamic table data capturing:
1.First of all Capture Table Head Count.
[int tHeadCount = driver.findElements(By.xpath("//table//tr//th")).size();]
2.Capture Table Row Count in which row your actual data exists.
[-in my point of view i need data from first row it self, so i am hard coding it to zero.]
If you want please add one for loop to existing code.
3.The actual solution starts from here.
Following is function call "Deposited By" is table heading text of corresponding table data.
String tableDataValue = managePackageTableData("Deposited By");
public String managePackageTableData(String columnName) {
//In Following line i am capturing table contains how many headers.
int tHeadCount = driver.findElements(By.xpath("//table//tr//th")).size();
int statusIndex = 0;
for(int i=0;i<tHeadCount-1;i++)
{
String theadValue = driver.findElements(By.className("table")).get(0).findElements(By.tagName("tr")).get(0).findElements(By.tagName("th")).get(i).getText();
if(theadValue.equalsIgnoreCase(columnName))
{
statusIndex = i;
break;
}
}
String tableData = driver.findElements(By.tagName("tbody")).get(0).findElements(By.tagName("tr")).get(0).findElements(By.tagName("td")).get(statusIndex).getText();
return tableData;
}
You have many options, but there's mine.
You catch all tds into a list.
List<WebElement> tdlist = driver.findElements(By.cssSelector("table[id='divListView'] tr td"));
and if you want to have the value, you can use a loop.
for(WebElement el: tdlist) {
Systeme.out.println(el.getText());
}
Check out this
Most common Challenge Automation tester face during iterating through Table and list. they often want to find some value from the table cell or list and want to perform action on the same value or find corresponding other element in the same block and perform action on it.
http://qeworks.com/iterate-table-lists-selenium-webdriver/
I have done this code using TestComplete and have replicated it now with Selenium C#, I have learnt this hard way but will work for any table control and you don't have to hardcode any xpath elements in it. Also if you have a nested table control within a td like for example where you have a nested table structure where your data is interpreted like below(happens in complex tables when you use developer express grids or angular grid controls).This case if you see the td tag again has a nested table structure which again has duplicate data. You can either capture such data or leave it depending on the case using the code which I am giving below.
Html
<table>
<tr>
<td>Account #
<table>
<tr>
<td>
Account #
</td>
</tr>
</table>
</td>
<td>Name
<table>
<tr>
<td>
Name
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>1234
<table>
<tr>
<td>
1234
</td>
</tr>
</table>
</td>
<td>Bharat
<table>
<tr>
<td>
Bharat
</td>
</tr>
</table>
</td>
</tr>
</table>
Code
public List<TableDataCollection> StoreHtmlTableToList(IWebElement tblObj)
{
DataTable dataTbl = new DataTable();
int rowIndex = 1;
try
{
_tblDataCollection = new List<TableDataCollection>();
var tblRows = ((IJavaScriptExecutor)DriverContext.Driver).ExecuteScript("return arguments[0].rows; ", tblObj);
if (tblRows != null)
{
//Iterate through each row of the table
foreach (IWebElement tr in (IEnumerable)tblRows)
{
int colIndx = 1;
// Iterate through each cell of the table row
var tblCols = ((IJavaScriptExecutor)DriverContext.Driver).ExecuteScript("return arguments[0].cells; ", tr);
foreach (IWebElement td in (IEnumerable)tblCols)
{
//loop through any child or nested table structures if you want using the same approach
//Write Table to List : This part is not done yet
//Print the values
Console.WriteLine("Row[" + rowIndex.ToString() + "] Col[" + colIndx.ToString() + "] : " + td.Text);
colIndx++;
}
rowIndex++;
}
}
}
catch (Exception)
{
throw;
}
return _tblDataCollection;
}
# Ripon Al Wasim
The below code will helps you to find values column by column
WebElement customtable = t.driver.findElement(By.cssSelector("div.custom-table"));
List<WebElement> r = customtable.findElements(By.tagName("tr"));
for (WebElement row : r) {
List<WebElement> d = row.findElements(By.tagName("td"));
for(int i = 0; i<d.size(); i++) {
if(i==0) {
WebElement x =d.get(i);
JavascriptExecutor js = (JavascriptExecutor) t.driver;
js.executeScript("arguments[0].scrollIntoView();", x);
System.out.println(i+"."+d.get(i).getText()+"\n");
if(d.get(i).getText().contains(searchtext)) {
System.out.println(i+".yes\n");
}
else
{
System.out.println("No\n");
}
}
}
}
its working for me.
//tbody/tr
this will give you the total no of row-
//tbody/tr/td
this will give you all the cell for the above rows and you can iterate it based on your requiredment.
Below are different approach we can follow to handle dynamic data in application [Its not for dynamic elements];
Using excel approach;
a. Get the web-element of the field
b. Get its text .
c. Store the data in the excel and validate with actual result pattern.
Note : There are multiple data validation options in excel like compare columns, get duplicate etc..
Using collection;
a. Get the web-element of the field.
b. Get its data inside the collection [List, set, map etc]
c. Write the java code to compare the pattern of the application data.
i. Pattern can be data type, data length, data range ,Decimal places of amount field or other ,currency type, date and time pattern etc.
ii. You can write the java conditions to verify the values of charts/graphs/dashboard if you are using in your application.
d. Compare the actual data pattern[from the collection] and the expected data pattern[From the java code]
Use JDBC API to handle it through the database where you can check the actual data by using different commands.

Categories

Resources