Tuesday 2 February 2016

Difference between findElement() and findElements() methods in selenium

findElement():
=============
1.By using findElement() method we can identify or we can locate one webelement in a current web page by using locationg mechanism
2.It identifies and returns that identified element in the form of WebElement means Returns a single WebElement.
Syntax: WebElement findElement(By by)

Example on findElement():
========================

package newselenium.topics;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FindElementDemo {
public static void main(String[] args) {

WebDriver webDriver = new FirefoxDriver();
webDriver.manage().window().maximize();
webDriver.manage().deleteAllCookies();
webDriver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);

webDriver.get("https://www.gmail.com");
// webDriver.navigate().to("https://www.gmail.com");

WebElement element_Gmail = webDriver.findElement(By.id("Email"));

element_Gmail.clear();

element_Gmail.sendKeys("rameshat914@gmail.com");

}
}




findElements():
===============

1.findElements() method finds all elements in a current page using locating mechanism

2.This method returns list of WebElements.

Syntax:java.util.List<WebElement> findElements(By by)



Example on findElements():
=========================

package com.verifications;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class LinksDemo {

public static void main(String[] args) throws InterruptedException {
int enableLinks=0;
int disableLinks=0;
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(45, TimeUnit.SECONDS);
driver.get("http://www.bing.com/");
List<WebElement> elements =driver.findElements(By.tagName("a"));
System.out.println(elements.size());
for (WebElement webElement : elements) {
System.out.println(webElement.getText());
if (webElement.isDisplayed()&&webElement.isEnabled()) {
enableLinks++;
}
else {
disableLinks++;
}
}
System.out.println("enabled links are:"+enableLinks);
System.out.println("disabled links are:"+disableLinks);
Thread.sleep(4000);
driver.quit();
}
}

No comments:

Post a Comment