Locating a WebElement With Selenium WebDriver

The following Selenium code in Java instructs the WebDriver to open the Firefox browser, go to the Mozilla Developer Network web page, find the WebElement “q” and perform a search for the query “html5.” The findElement method is very specific in that it only find one element using the By object. If zero elements are found, an error will be generated. It will also only find the first element if multiple elements match the search criteria. For finding zero to multiple elements specified by the By object, findElements should be used instead, note the plural versus singular version.

package net.brav3.webdriver.A1;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class MDNSearch {
	public static void main(String[] args) {
		WebDriver driver = new FirefoxDriver();
		driver.get("https://developer.mozilla.org");
		WebElement searchBox = driver.findElement(By.name("q"));
		searchBox.sendKeys("html5");
		searchBox.submit();
	}
}

The following is a demonstration of the findElement(s) method which finds multiple elements of the same search criteria. The type of searchBoxes is an ArrayList which is different from regular arrays in that regular arrays are fixed size. ArrayList can be dynamic in size as the content of the array changes. In your Java console you’ll notice there are two search boxes with the name of “q.”

package net.brav3.webdriver.A1;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FindMultipleElements {
	public static void main(String[] args) {
		WebDriver driver = new FirefoxDriver();
		driver.get("https://developer.mozilla.org");
		java.util.List<WebElement> searchBoxes = driver.findElements(By.name("q"));
		System.out.println(searchBoxes.getClass().getName());
		System.out.println(searchBoxes.size());
		System.out.println(searchBoxes);
	}
}

Leave a Comment





This site uses Akismet to reduce spam. Learn how your comment data is processed.