What are Find Element and Find Elements in Selenium?
The pre requisite of Find Element and Find
Elements, we need to understand what is a WebElement. WebElement is an
interface, and it represents an HTML element on a web page. We can find the
WebElement by searching it in the DOM source. The WebDriver API provides
built-in methods for it.
Find Element
The Find Element helps to find a web
element(one) and returns the WebElement
reference. It finds the first
matching web element on the web page.
Syntax
: webelement element = driver.findelement(by.locator(“value”));
Here, By is a class in WebDriver. It has the
mechanism to locate a web element. It uses various locator strategies to locate
the element. The locator strategy may include values like,
- Id
- Name
- Class Name
- Tag Name
- Link Text
- Partial Link Text
- Xpath
The locator value helps to identify a web
element uniquely. These values are found by referring to the HTML source code
of the element. Example of a web element command
Example : WebElement username =
driver.findElement(By.name("user"));
Find Elements :
The Find Elements helps to find web
elements(more than one) and returns a list of web elements
Syntax : list< webelement> element = driver.findelements(by.locator(“value”));
Ex
: list<WebElement> links = driver.findElements(By.tagname("a"));
In the above example, it finds the list of all
links present on the web page using the tag name, “a”.
Code
for the better understanding :
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class findelements{
public static void main (string
args[])
{
WebDriver
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://google.com/");
List listOfLinks = driver.findElements(By.tagName("a"));
WebElement thirdlink = listOfLinks.get(3);
System.out.println(thirdlink.getText());
List listOfLinks = driver.findElements(By.tagName("a"));
WebElement thirdlink = listOfLinks.get(3);
System.out.println(thirdlink.getText());
for(int
i=0;i<listOfLinks.size();i++) {
WebElement link = listOfLinks.get(i);
System.out.println(link.getText());
}
}
}
WebElement link = listOfLinks.get(i);
System.out.println(link.getText());
}
}
}
Difference between Find Element and Find Elements
Find Element
|
Find Elements
|
1. It returns
a single element on the web page.
|
1. It returns
a list of elements on the web page.
|
2. It finds
the first matched web element.
|
2. It finds
all the web elements that match.
|
3. It doesn’t
require indexing.
|
3. These
elements are indexed from 0 and can be get using get().
|