Get TH index number using Xpath in selenium - java

Hi I just want to get the index number of TH column using unique Xpath. Like A loop will run and check on which TH column Xpath match and return the index number. Is there any way i can do this in selenium ? Till now im able to get the tag index and run the the loop but now I have check the on each TH with xpath rather its matched or not and give me the index number. Please let me know is there anything with Im able to achieve this with this logic or any other any Xpath techniques.
Table = driver.findElement(By.xpath("//table/thead[#class='ui-datatable-thead']"))
List<WebElement> rows_head = Table.findElements(By.tagName('th'))
int head_size= rows_head.size()
System.out.println(head_size);
for (int c = 1; c <= head_size; c++) {
driver.findElement(By.xpath(
"//th[4][#class='ui-state-default ui-unselectable-text ui-sortable-column']")
)
// Here is something I want loop will check the each TH with above given
// Xapth and return the TH index in the table on match TH xpath index.
}

Selenium doesn't supply an API to return the xpath of found element. So you can't archive your goal by comparing xpath.
But Selenium supply API to get the attribute value of found element, you can compare with it to see it's your desired element or not.
WebElement thead = driver.findElement(By.xpath("//table/thead[#class='ui-datatable-thead']"));
List<WebElement> heads = thead.findElements(By.tagName('th'));
int head_size= heads.size()
System.out.println(head_size);
String expectedClass = "ui-state-default ui-unselectable-text ui-sortable-column"
int i = 1;
for (; i <= head_size; i++) {
if(heads[i].getAttribute("class").equal(expectedClass))
// check attribute class value is as expect
// you can change to other attribute or check more than one attribute
break;
)
}
System.out.println("Matched th index: " + i);

Related

How do I select a specific element from a set with similar XPath paths?

There are 2 drop-down lists. Each has a similar meaning, for example, "Jorge". Lists in different modules. When I need to fill in, for example, a list that is lower in the tree, then the first match is taken along the XPath path, on an undisclosed list.
Not lists, but values in drop-down lists!
There are 2 drop-down lists. Each has a similar meaning, for example, "Jorge". Lists in different modules. When I need to fill in, for example, a list that is lower in the tree, then the first match is taken along the XPath path, on an undisclosed list.
Not lists, but values in drop-down lists!
I wanted to implement it in Java this way:
Example:
if (findElement(By.xpath("(//example//example)")).isDisplayed()) {
findElement(By.xpath("(//example//example)")).click();
}
But in this case, the element is not displayed.
How to implement a search of all values similar to the XPath path in order to get the one that is displayed?
I tried to do something like this: (//example//example)1 (//example//example)[2] (//example//example)[3]
In my case, we have that 1 - the element does not exist [2] - exists, but is not displayed (isDisplayed = false) [3] - exists, is displayed (isDisplayed = true)
iterating through the values in the loop for [n] cannot be implemented, because, for example, the value 1 is not.
Described as difficult as possible :D. Excuse me.
If someone understands my nonsense, please help me. How to implement my requirement?
enter image description here
UPD:
The problem was solved (for me) by substituting the first value into the expression ()"{1}" immediately.
Now I'm interested in why I get an exception after the first iteration:
Method threw 'org.openqa.selenium.ElementNotInteractableException' exception.
Code:
int number = 1;
String option = "(//ul[contains(#style, 'display: block')]//li//span[contains(text(),'" + valueField + "') or strong[contains(text(),'" + valueField.toUpperCase() + "')]])";
findElement(By.xpath(option+"["+number+"]"));
String[] words = valueField.split(" ");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < words.length; i++) {
builder.append(words[i]);
setFieldByLabel(nameModule, nameLabel, builder.toString());
fastWaitLoading();
for (int y = 0; y < 10; y++) {
if (findElement(By.xpath(option+"["+number+"]")).isDisplayed()) {
new Actions(browser.getWebDriver())
.moveToElement(findElement(option))
.click()
.build()
.perform();
break;
}
number++;
}
}
So I am trying to fully understand your question, and I don't. What I would recommend for a situation like this is, iterate through all elements by creating a list with: findElements(By.xpath ... )
This way you will get a list of webelements and you can iterate through them. Then apply a foreach, assert if element is displayed (it exists as it has been found with findElements) and you should be able to interact with it.
Yeah, everything is in a prominent place)
Missed it
new actions(browser.getWebDriver()) .moveToElement(findElement(**option**)) .click() .build() .perform(); break;
Here
new actions(browser.getWebDriver())
.moveToElement(findElement(**option + "[" + number+"]"**))
.click()
.build()
.perform();
break;

How to find no. Of elements starts with land in selenium drop-down and count them

Select se= new select(locator of drop-down);
List<webelemts> list= se.getoptions();
For(int l: list){}
Not sure as I want to select all countries starts ends with land and count the no. Of them and print.
You can simply create a int counter and initial value will be set to 0.
also using the below for each loop, you can iterate all the options and using .getText() method, you can use .startsWith or .endsWith like below.
int counter = 0;
Select se = new Select(driver.findElement(By.xpath("select web element xpath here")));
List<WebElement> list = se.getOptions();
for (WebElement ele : list) {
if(ele.getText().startsWith("land") || ele.getText().endsWith("land")) {
counter++;
}
}
and then finally print the counter,
System.out.println(counter);

skipping first row of a html table Java

I am still learning xpath and I am trying to skip the first row of a table because the first row has no values. I am not having success i searched through stack over flow and could not find anyone with a similar issue. My code is below:
int reqIndex = 0;
do {
List<WebElement> payDates = driver.findElements(By.xpath("//tr[starts-with(#id,'changeStartWeekGrid_row_')]/td[contains(#id,'_cell_4')/span]"));
System.out.println(payDates);
for(WebElement pd:payDates) {
LocalDate localDate = LocalDate.now();
java.util.Date d = new SimpleDateFormat("yyyy-MM-dd").parse(localDate.toString());
String str = pd.getText();
if ( str >= (d) ){ // still figuring this out
driver.findElement(By.xpath( "//tr[#id='changeStartWeekGrid_row_'" + reqIndex +"])/TBODY[#id='changeStartWeekGrid_rows_tbody']/TR[7]/TD[1]/DIV[1]/DIV[1]/DIV[1]")).click();
break;
}else{
reqIndex++;
}
}
}while(reqIndex < 7 ); /// do this 7 times
Thread.sleep(10000);
This is the part i am trouble shooting right now
List<WebElement> payDates = driver.findElements(By.xpath("//tr[starts-with(#id,'changeStartWeekGrid_row_')]/td[contains(#id,'_cell_4')/span]"));
System.out.println(payDates);
Thread.sleep(10000);
The xpath works the problem is that it is selecting the first row and it has no values row zero does so it needs to skip the first row and go to row zero.
when i run the code i get this message:
( //tr[starts-with(#id,'changeStartWeekGrid_row_')]/td[contains(#id,'_cell_4')/span])
ilter expression must evaluate to nodeset.
the row highlighted is the row i am trying to skip
cell 4 image
-----radio button html code below
<div id="changeStartWeekGrid.store.rows[5].cells[0]_widget" tabindex="0" class="revitRadioButton dijitRadio" onfocus="var registry = require('dijit/registry'); registry.byId('changeStartWeekGrid').changeActiveCell('changeStartWeekGrid_row_5_cell_0', event);" onblur="var registry = require('dijit/registry'); registry.byId('changeStartWeekGrid').blurActiveCell('changeStartWeekGrid.store.rows[5]', 'changeStartWeekGrid.store.rows[5].cells[0]');"><div class="revitRadioButtonIcon"></div></div>
---radio button picture
Try to use XPath
//table[#id='changeStartWeekGrid_rows_table']//tr[preceding-sibling::tr]
to select all tr nodes except the firts one
You can also use position() as below:
//table[#id='changeStartWeekGrid_rows_table']//tr[position()>1]
Note that in XPath indexation starts from 1 and so [position()>1] predicate means return all sibling nodes skiping the first one
You may also use
//tr[starts-with(#id,'changeStartWeekGrid_row_') and not(starts-with(#id, 'changeStartWeekGrid_row_column'))]/td[5]/span

Selenium - How to count the number of rows in a table dynamically?

In my html page there's a table with 10 rows; those rows will display based on filter (dynamically). Let's say, for example, without any filters by default 10 row will be returned.
after applying the filter, less than 10 rows will be returned, depending on the type of filter, so i want to get that dynamic count of table rows (after filter) using selenium web driver.
i tried with driver.findElements(By.xpath("abcd")).size() but this is giving default count 10; however, after applying the filter only 2 rows are appearing.
Please suggest how to get dynamic count (count=2 as appearing 2 rows in UI) .
To find the total number of elements on dynamic webpage we need to use driver.findElements().size() method. But sometimes it's not useful at all.
First get the size of all element matching with the row count. Once we have it then you can use dynamic xpath ie replace row and column number run time to get the data.
{
List<WebElement> rows_table = mytable.findElements(By.tagName("tr"));
//To calculate no of rows In table.
int rows_count = rows_table.size();
//Loop will execute till the last row of table.
for (int row=0; row<rows_count; row++){
//To locate columns(cells) of that specific row.
List<WebElement> Columns_row = rows_table.get(row).findElements(By.tagName("td"));
//To calculate no of columns(cells) In that specific row.
int columns_count = Columns_row.size();
System.out.println("Number of cells In Row "+row+" are "+columns_count);
//Loop will execute till the last cell of that specific row.
for (int column=0; column<columns_count; column++){
//To retrieve text from that specific cell.
String celtext = Columns_row.get(column).getText();
System.out.println("Cell Value Of row number "+row+" and column number "+column+" Is "+celtext);
}
System.out.println("--------------------------------------------------");
}
I'll prefix this with the fact that I'm not a Java dev but I use a lot of webdriver in other languages.
The best way to setup tests is to wait for the outcome of the action that your testing. Sometimes you can get away without doing waits, or timed waits, but then you go and run your tests on a slower grid box and everything falls in a heap.
Things like "div exists", "div has class", whatever your outcome may be. In your case, it sounds like you may not be able to test for a div to be rendered but you can probably use your size test as the outcome to wait for.
Selenium can use any ExpectedCondition or you can specify a function
WebDriverWait wait = new WebDriverWait(getDriver(), 5);
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
int elementCount = driver.findElement(By.xpath("xxxx")).size();
if (elementCount == 2)
return true;
else
return false;
}
});
Code from https://sqa.stackexchange.com/a/8701

GWT DOM not working

I want to append div inside <TH> in GWT
Element tr = DOM.createTR();
DOM.appendChild(thead, tr);
for (int index = 0; index < headers.size(); index++) {
Element th = DOM.createTH();
Element div = DOM.createDiv();
DOM.appendChild(th, div); // this is not working !
DOM.appendChild(tr, th);
}
Is any thing wrong in my code?
I assume it will give you compile time error because the method `DOM.appendChild(th, div);' second parameter should be part of package structure:
com.google.gwt.user.client.Element
instead of
com.google.gwt.dom.client.Element

Categories