Reputation: 11
Not able to iterate through WebElement List
Hi
I am doing some action on https://www.makemytrip.com/ under Departure. When click on Departure, it will show calendar of two months.
I am able to get two webElements with same xpath as mentioned below, now I want to go one by one, and getText()
to match with user month name.
List<WebElement> month_list= driver.findElements(By.xpath("//div[@class='DayPicker-Month']"));
ListIterator<WebElement> listIter= month_list.listIterator();
while(listIter.hasNext()) {
WebElement elem= listIter.next();
System.out.println(elem.findElement(By.xpath("//div[@class='DayPicker-Caption']/div")).getText());
}
But every time, it is reporting same text :
July 2019
July 2019
However, I am expecting it should report :
July 2019
August 2019
Please guide me how can I perform anything on each element one by one.
Upvotes: 1
Views: 1395
Reputation: 497
You can Try using,
List<WebElement> monthname= driver.findElements(By.xpath("//div[@class='DayPicker-Caption']"));
After Storing in List of Webelements you can use different kind of for Loops for getting the text.But the best preference is forEach Loop and for Iterative Loop.
forEach Loop:
for(WebElement months: monthname)
{
System.out.println(months.getText())
}
General forLoop
int length= monthname.size();
for (int i = 0; i<length; i++)
{
String name = monthname.get(i);
System.out.println(name);
}
PS: But The Best Preference is to go with forEachLoop Rather than General For Loop
.
Upvotes: 0
Reputation: 105
you can make use of foreach loop. Try the below code
for(WebElement monthName: month_list)
System.out.println(monthName.getText())
P.S. I doubt your Xpath ,the xpath which you wrote is the entire month calendar(that is the month name , the dates , the prices on each dates so its the entire div that you have picked)
Kindly try
List<WebElement> month_list= driver.findElements(By.xpath("//div[@class='DayPicker-Caption']"));
Upvotes: 0
Reputation: 23815
You should try using .
instead of /
in you second xpath
as below :-
System.out.println(elem.findElement(By.xpath("./div[@class='DayPicker-Caption']/div")).getText());
Absolute vs relative XPaths (/ vs .)
/
introduces an absolute location path, starting at the root of the document..
introduces a relative location path, starting at the context node.Upvotes: 1