What is the difference between findElement and findElements in…
There are differences between findElement and findElements in the 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.
Good usage of the 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"));
Example
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(); } }