|
Answer» Following table lists the differences between findElement() and findElements() in SELENIUM : | findElement() | findElements() |
|---|
| The first web element that matches the locator is returned. | It GIVES you a list of all the web items that match the locator. | | If there are no matching web elements, a NoSuchElementException is produced. | If there are no matching elements, an empty list is returned. | | Syntax − WebElement button = webdriver.findElement(By.name("<<Name value>>")); | Syntax − List<WebElement> buttons = webdriver.findElements(By.name("<<Name value>>")); | // JAVAimport org.openqa.selenium.By;import org.openqa.selenium.Keys;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.chrome.ChromeDriver;import java.util.concurrent.TimeUnit;public class findElements { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\vaibhav\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://www.exampleurl.com/example.htm"; driver.get(url); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); List<WebElement> rows = driver.findElements(By.xpath("//table/tbody/tr[2]/td")); // xpath with INDEX appended to get the values from the row 1of table using findElements(), which returns a list System.out.println("The number of values in row 2 is "+ rows.size()); driver.close(); }}Explanation - In the above code, first of all, we import all the necessary headers and then set up the driver for the chrome browser. We use the findElements() method to find all the values present in the 2nd row of a table in the given URL web page using the XPath of the element. import org.openqa.selenium.By;import org.openqa.selenium.Keys;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.chrome.ChromeDriver;import java.util.concurrent.TimeUnit;public class findTagname { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\vaibhav\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://www.exampleurl.com/example.htm"; driver.get(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); driver.findElement(By.cssSelector("input[ID='search']")).sendKeys("Selenium"); //Using id tagname attribute combination for css expression and get the element from findElement() driver.close(); }}Explanation - In the above code, first of all, we import all the necessary headers and then set up the driver for the chrome browser. We use the findElement() method to find an input element having an id attribute set as search.
|