Verify the table column order from selenium - java

Requirement is to verify the column order of the following table is in the correct order from its column header names.
Therefore, I have written down a method to cover up my requirement, which accepts an array list [String] of the table header names in the required order.
But it apparently does not do my requirement through the soft-Asserts as 'isDisplayed()' method is always returning 'false'.
Can anyone suggest me kindly further points to modify it and to get it fixed?
HTLM Code for the table :
<table id="examMarkEntryExamList" class="display table table-bordered table-striped dynamic-table display_header_class">
<thead>
<tr>
<th class="text-center sortable sorted order1">Academic Year</th>
<th class="text-center sortable sorted order1">Curriculum</th>
<th class="text-center sortable sorted order1">Grade</th>
<th class="text-center sortable sorted order1">Semester/Term</th>
<th class="text-center sortable sorted order1">
<a class="pagination-cuser-point">Exam Code</a>
</th>
<th class="text-center sortable sorted order1">Actions</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>2016-2016</td>
<td>LOCAL</td>
<td>GRADE11</td>
<td>2nd Term</td>
<td>G11SecondTerm</td>
<td>
</tr>
</tbody>
</table>
Selenium [Java] method to verify the column order
public void verifyColumnOrder(WebDriver driver, String tableId, ArrayList<String> columnHeaderList) {
SoftAssert softassert = new SoftAssert();
String relativeXpath = "//table[contains(#id,'"+tableId+"')]/";
for (String columnHeader : columnHeaderList) {
relativeXpath = relativeXpath + "/following-sibling::th[contains(.,'" + columnHeader + "')]";
softassert.assertTrue(driver.findElement(By.xpath(relativeXpath)).isDisplayed());
}
softassert.assertAll();
}

An other solution would be to directly get the text of thead with getText(). It will return a concatenation of all the visible titles which will be easier to compare:
public void verifyColumnOrder(WebDriver driver, String tableId, ArrayList<String> columnHeaderList) {
String expectedHeaders = String.join(" ", columnHeaderList);
String visibleHeaders = driver.findElement(By.cssSelector("[id='" + tableId + "'] thead")).getText();
Assert.assertEquals(visibleHeaders, expectedHeaders);
}

The xpath you are using is incorrect. th is not a sibling of table tag. It is 2 levels inside.
Try this CSS locator - "table[id='examMarkEntryExamList'] th". You can use it directly by using By.cssSelector or xpath "//table[#id='examMarkEntryExamList']//th".
Use this locator to get a List of webelements. From this get the list of text in the th tags.
List<WebElement> thelem = driver.findElements(By.xpath....);
List<String> thText = thelem.stream().map(e -> e.getText()).collect(toList());
Just assert -- `softassert.assertTrue(thText.equals(columnheaders));
Please check actual syntax.

Related

Populating inner table inside another table with Thymeleaf

I have DTO class:
private LocalDate date;
private List<String> firstShift;
private List<String> secondShift;
private List<String> thirdShift;
With getters, setters and toString for every field.
I'm creating this table for shift schedule calendar:
My Thymeleaf:
<table class = "table table-striped table-hover" id = "schedule_table">
<thead>
<tr>
<th class = "th_schedule_table">Date</th>
<th class = "th_schedule_table">First Shift</th>
<th class = "th_schedule_table">Second Shift</th>
<th class = "th_schedule_table">Third Shift</th>
</tr>
</thead>
<tbody>
<tr th:each = "calendar_node : ${calendarNodeList}">
<td th:text = "${calendar_node.date}"></td>
<td>
<table>
<tbody>
<tr th:each = "employee, i : ${firstShift}">
<td th:text = "${firstShift.[i]}"></td>
</tr>
</tbody>
</table>
</td>
<td>
<table>
<tbody>
<tr th:each = "employee: ${secondShift}">
<td th:text = "${employee}"></td>
</tr>
</tbody>
</table>
</td>
<td>C</td>
</tr>
</tbody>
</table>
The idea behind this: CalendarNode.date generates row for parent table, for each date. That works fine.
Inside every row, in a cell I have second table that should show list of employees who works on that date in that shift. If I have calendar_node object in one row, I'm using his "firstShift" field to generated rows for second inner table.
The problem is that I'm getting empty table. I checked my back-end and I have two employees for first date (18th July), first shift, one employee for second shift, but none is shown. I tried a lot of different syntax for Thymeleaf, none of it works. I guess I did Thymeleaf wrong?
UPDATE:
Example of data that has been passed to web page via model object:
If firstShift is a field of calendar_node, then you need to actually address it as such in the template:
${calendar_node.firstShift} instead of ${firstShift}

selenium - select a column by header

In my script (selenium & Java) I need to select a table column by it's header.
Basically, I send the header as a parameter and then just fetch through that column.
But, the problem is that I'm not able to get the header column's index.
Any idea or suggestion?
<table class="table table-hover tablesorter ib-table" data-reactid=".0.0.0.1.2.0">
<thead data-reactid=".0.0.0.1.2.0.0">
<tr data-reactid=".0.0.0.1.2.0.0.0">
<th data-reactid=".0.0.0.1.2.0.0.0.0">ID</th>
<th data-reactid=".0.0.0.1.2.0.0.0.1">To</th>
<th data-reactid=".0.0.0.1.2.0.0.0.2">From</th>
<th data-reactid=".0.0.0.1.2.0.0.0.3">Text</th>
</tr>
</thead>
<tbody data-reactid=".0.0.0.1.2.0.1" style="height: auto;">
<tr data-reactid=".0.0.0.1.2.0.1.$0">
<td data-reactid=".0.0.0.1.2.0.1.$0.0">123456</td>
<td data-reactid=".0.0.0.1.2.0.1.$0.1">+0156477889785</td>
<td data-reactid=".0.0.0.1.2.0.1.$0.2">+0156477889784</td>
<td data-reactid=".0.0.0.1.2.0.1.$0.3">sample textM</td>
</tr>
<tr data-reactid=".0.0.0.1.2.0.1.$1">
<tr data-reactid=".0.0.0.1.2.0.1.$2">
First you need to do a List that has all the headers by
List<WebElement> headersList = driver.findElement(By.xpath("//table[#class='table-hover tablesorter ib-table']")).findElements(By.tagName("th"));
after that you going threw all the tr in loop
List<WebElement> trList = driver.findElement(By.xpath("//table[#class='table-hover tablesorter ib-table']")).findElements(By.tagName("tr"));
List<WebElement> tdList;
for(int = i ; i < trList.Count ; i++)
{
tdList = trList[i].findElements(By.tagName("td"));
//tdList[0] its header in index[0]... and so on...
}
This will not work in odd cases such as when using colspan. It should work for any "normal" table of data. The trim is in use for avoiding the inevitable whitespace that appears around many WebElements.
public static List<WebElement> getColumnByHeaderText(WebDriver driver, By by, String header) {
WebElement table = driver.findElement(by);
Function<WebElement, String> elementToString = (WebElement w) -> w.getText().trim();
List<WebElement> list = table.findElements(By.tagName("th"));
int index = Lists.transform(list, elementToString).indexOf(header);
if (index == -1) {
throw new RuntimeException("Unable to locate header");
} else {
return table.findElements(By.cssSelector("td:nth-child(" + (index + 1 ) + ")"));
}
}

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.

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.

Jsoup - read one by one

I'm starting to use Jsoup recently. I need list some elements in a HTML source. For example:
<table class="list">
<tr>
<td class="year" colspan="5">2012</td>
</tr>
<tr>
<td class="code">COMP0348</td>
<td class="name">Software Engineering</td>
</tr>
<tr>
<td class="code">COMP0734</td>
<td class="name">System Information</td>
</tr>
<td class="year" colspan="5">2013</td>
</tr>
<tr>
<td class="code">COMP999</td>
<td class="name">Windows</td>
</tr>
</table>
This is what I want:
2012
Comp0348 Software Engineering
COMP0734 System Information
2013
COMP999 Windows
But in my code, it's not list one by one, it's list one string containing first all "year", and after in another line containing all "code" and after in another line all "name".
Like:
2012
Comp0348 COMP0734 COMP999
Software Engineering System Information Windows
How can I do this?
I guess you only select the tags by criteria, but not the structure.
But see here:
Document doc = ...
Element table = doc.select("table.list").first(); // select the table
for( Element element : table.select("tr") ) // select all 'tr' of the table
{
final Elements td = element.select("td.year"); // select the 'td' with 'year' class
if( !td.isEmpty() ) // if it's the one with the 'year' class
{
final String year = td.first().text(); // get year
System.out.println(year);
}
else // if it's another 'tr' tag containing the 'code' and 'name' element
{
final String code = element.select("td.code").first().text(); // get code
final String name = element.select("td.name").first().text(); // get name
System.out.println(code + " " + name);
}
}
Output (using your html):
2012
COMP0348 Software Engineering
COMP0734 System Information
2013
COMP999 Windows

Categories

Resources