Showing posts with label findelement and findelements. Show all posts
Showing posts with label findelement and findelements. Show all posts

Tuesday 7 January 2014

Difference between find element () and findelements ()

Difference between find element () and find elements ()?
findElement() :
Find the first element within the current page using the given "locating mechanism".
Returns a single WebElement.
Syntax: WebElement findElement(By by)
Ex:
driver.get("http://ruchi-myseleniumblog.blogspot.in/"); 
WebElement widget = driver.findElement(By .xpath(".//*[@id='BlogArchive1_ArchiveList']"));
widget.click();
findElements() :
Find all elements within the current page using the given "locating mechanism".
Returns List of WebElements.
Syntax: 
        WebElement ullist = driver.findElement(By.className("posts"));
List<WebElement> posts = ullist.findElements(By.tagName("li"));
System.out.println("List of Posts are Below");
for (int i = 0; i < posts.size(); i++) {
String post = posts.get(i).findElement(By.tagName("a")).getText();

System.out.println(post);
}

Sample Program:

package programs;

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class Sample {
WebDriver driver;

@Test
public void test() {

driver = new FirefoxDriver();
driver.get("http://ruchi-myseleniumblog.blogspot.in/");
WebElement widget = driver.findElement(By
.xpath(".//*[@id='BlogArchive1_ArchiveList']"));
WebElement hierarchy = widget.findElement(By.className("hierarchy"));
System.out.println("Year is "
+ hierarchy.findElement(By.className("post-count-link"))
.getText());
System.out.println("Year-Posts size  is "
+ hierarchy.findElement(By.className("post-count")).getText());
WebElement sublist = hierarchy.findElement(By.className("hierarchy"));
System.out.println("Month is "
+ sublist.findElement(By.className("post-count-link"))
.getText());
System.out.println("Month-Posts size  is "
+ sublist.findElement(By.className("post-count")).getText());
WebElement ullist = driver.findElement(By.className("posts"));
List<WebElement> posts = ullist.findElements(By.tagName("li"));
System.out.println("List of Posts are Below");
for (int i = 0; i < posts.size(); i++) {
String post = posts.get(i).findElement(By.tagName("a")).getText();

System.out.println(post);
}
driver.close();
}


}