Be Brav3

Locating a WebElement With Selenium WebDriver

March 09, 2016

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.

[java highlight=”11″]

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();
}

}

[/java]

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.”

[java highlight=”11″]

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 searchBoxes = driver.findElements(By.name(“q”));
System.out.println(searchBoxes.getClass().getName());
System.out.println(searchBoxes.size());
System.out.println(searchBoxes);
}

}

[/java]