Saturday, 18 July 2015

Diffrence between FindElement and FindElements

 Difference between FindElement and FindElements

 

findElement() :   

  • Syntax: WebElement findElement(By by)    
  • Find the first element within the current page using the given "locating mechanism"
  • Returns a single WebElement  
  • Throws a runtime exception NOSuchElementException when element is not found
  • Input parameter is instance of By class
  • We use findElement method frequently in our webdriver to find a Web element

findElements() :   

  • Syntax: java.util.List<WebElement> findElements(By by)
  • Find all elements within the current page using the given "locating mechanism"
  • Returns Empty list when no matching elements found or list of web elements when match found
  • NO exception throws when element is not found
  • Input parameter is instance of By class
  • We use findElements method occasionally to find out list of web elements, E.g: List of Links,buttons,..,

Examples of findElement() and findElments() methods:

 

1.    findElement()

Let's see how the code looks like to find out the first web element tag name on a Google Search page because It find’s the first element within the current page using the given "locating mechanism"

public class GoogleSearchPageByTagName{
 public static void main(String[] args){
        IWebDriver driver = null;  
           driver  = new ChromeDriver(@"C:\ChromDriverSelenium");
           driver.Navigate().GoToUrl("http://www.google.com");
           IWebElement webelement= driver.FindElement(By.TagName("input"));
           Console.WriteLine("Tag name is" + webelement.TagName);
           Console.ReadLine();
        driver.Quit();
   }
}

2.    findElments()

 

Let's see how the code looks like to find out the number of input tags present on a Google Search page.
 public class GoogleSearchPageByTagName{
        static void Main(string[] args)
      
        {
           
           IWebDriver driver = null;  
           driver  = new ChromeDriver(@"C:\ChromDriverSelenium");
           driver.Navigate().GoToUrl("http://www.google.com");
           IList<IWebElement> Tags= driver.FindElements(By.TagName("input"));
           Console.WriteLine("Total input Tags" + Tags.Count());
           Console.ReadLine();
           driver.Quit();

        }
       
    }

No comments:

Post a Comment