
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference Between Find Element and Find Elements in Selenium
There are differences between findElement and findElements method in Selenium webdriver. Both of them can be used to locate elements on a webpage. The findElement points to a single element, while the findElements method returns a list of matching elements.
The return type of findElements is a list but the return type of findElement is a WebElement. If there is no matching element, a NoSuchElementException is thrown by the findElement, however an empty list is returned by the findElements method.
A good usage of findElements method usage is counting the total number of images or accessing each of images by iterating with a loop.
Syntax
WebElement i = driver.findElement(By.id("img-loc")); List<WebElement> s = driver.findElements(By.tagName("img"));
Code Implementation
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import java.util.List; public class FindElementFindElementMthds{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java \chromedriver.exe"); WebDriver driver = new ChromeDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.tutorialspoint.com/upsc_ias_exams.htm"); //identify single element WebElement elm = driver.findElement(By.tagName("h2")); String s = elm.getText(); System.out.println("Get text on element: " + s); //identify all elements with tagname List<WebElement> i = driver.findElements(By.tagName("img")); //count int c = i.size(); System.out.println("Number of images: " + c); //browser close driver.close(); } }
Output
Advertisements