We have seen many examples of webdriver's findElement() in my previous posts. You will find syntax of findElement() with example on THIS PAGE if you wants to use it in your software web application test case. Selenium WebDriver software testing tool has one more related method findElements. Now main question is what is the difference between findElement and findElements methods in selenium 2 software automation tool? First of all let me provide you difference description and then example.
findElement() method
- We need to use findElement method frequently in our webdriver software test case because this is the only way to locate any element in webdriver software testing tool.
- findElement method is useful to locating targeted single element.
- If targeted element is not found on the page then it will throw NoSuchElementException.
findElements() method
- We are using findElements method just occasionally.
- findElements method will return list of all the matching elements from current page as per given element locator mechanism.
- If not found any element on current page as per given element locator mechanism, it will return empty list.
Now let me provide you simple practical example of findElement method and findElements method to show you clear difference. You can VIEW ALL PRACTICAL EXAMPLES OF SELENIUM WEBDRIVER one by one.
Copy bellow given @Test method part of findElement and findElements method examples and replace it with the @Test method part of example given on THIS PAGE. (Note : @Test method is marked with pink color in that linked page).
@Test
public void test () throws InterruptedException
{
WebElement option = driver.findElement(By.xpath("//option[@id='country5']"));
System.out.print(option.getAttribute("id")+" - "+option.getText());
List<WebElement> options= driver.findElements(By.xpath("//option"));
System.out.println(options.size());
for(int i=0;i<=options.size();i++)
{
String str = options.get(i).getAttribute("id")+" - "+options.get(i).getText();
System.out.println(str);
}
}
In above example, findElement will locate only targeted element and then print its id and text in console while findElements will locate all those elements of current page which are under given xpath = //option. for loop is used to print all those element's id and text in console.
Same way you can locate all input elements, link elements etc.. using findElements method.
Hi Aravind,
ReplyDeleteThere is an error in your code:
for(int i=0;i<=options.size();i++)
Result = java.lang.IndexOutOfBoundsException. Index is identical to size.
This should be:
for(int i=0;i<options.size();i++)
Because the index of the list starts from zero.
Regards,
Geoffrey
good blog.
DeleteOne more point. Never use Assert in these kind of For loops.
Good catch Geoffrey
ReplyDelete