Reputation: 479
I am fetching date webelements from facebook and I am looping it by using the below code.
public class select_facebook {
public static void main(String[] args) throws Exception {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.facebook.com");
List<WebElement> days = driver.findElements(By.xpath("//select[@id='day']"));
System.out.println(days.size());
for (int i=0;i<days.size();i++) {
System.out.println(days.get(i));
}
}
}
But I get output as
1
[[FirefoxDriver: firefox on XP (58765a0e-31a0-40bc-8565-3418ae54682c)] -> xpath: //select[@id='day']]
But same code in for loop if I use System.out.println(days.get(i).gettext());
It list all the dates 1 to 31.
My question is then why should I call this as
List<WebElement> days = driver.findElements(By.xpath("//select[@id='day']"));
Because even the size of the webElements is just :1
System.out.println(days.size());
instead I could have called it as
WebElement days = driver.findElement(By.xpath("//select[@id='day']"));
Upvotes: 0
Views: 4844
Reputation: 2627
You should have to focus on what you exactly need. If you want more elements use FindElements()
and when you are interested in only one element then use FindElement()
.
If there are more number of elements and if you use FindElement()
it returns you very first element and rest others are get neglected. So make sure about your requirement.
This is because an id value can be given to only one HTML element. In other words, multiple elements cannot have the same id value on the same page in valid HTML DOM only.
FindElement()
it returns you WebElement:
WebElement SINGLEELEMENT= driver.findElement(By.SELECTOR("//TAGNAME[@ATTRIBUTENAME='ATTRIBUTEVALUE']"));
FindElements()
it returns you WebElements i.e List<WebElement>
of multiple elements. It return 1 if only one element present in it or multiple if presents more:
List<WebElement> LISTOFELEMENTS= driver.findElements(By.SELECTOR("//TAGNAME[@ATTRIBUTENAME='ATTRIBUTEVALUE']"));
You can put looping on it to get each one element and work on each individually.
Upvotes: 1
Reputation: 120
You will get list of Elements in return of
List<WebElement> days = driver.findElements(By.xpath("//select[@id='day']"));
because there could be more than 1 element by same id ('day').
Upvotes: 1