Saturday, January 11, 2014

User Input - Filling In Forms


We’ve already seen how to enter text into a textarea or text field, but what about the other elements? You can “toggle” the state of checkboxes, and you can use “click” to set something like an OPTION tag selected. Dealing with SELECT tags isn’t too bad:
WebElement select = driver.findElement(By.tagName("select"));
List<WebElement> allOptions = select.findElements(By.tagName("option"));
for (WebElement option : allOptions) {
    System.out.println(String.format("Value is: %s", option.getAttribute("value")));
    option.click();
}
This will find the first “SELECT” element on the page, and cycle through each of its OPTIONs in turn, printing out their values, and selecting each in turn. As you will notice, this isn’t the most efficient way of dealing with SELECT elements. WebDriver’s support classes include one called “Select”, which provides useful methods for interacting with these.
Select select = new Select(driver.findElement(By.tagName("select")));
select.deselectAll();
select.selectByVisibleText("Edam");
This will deselect all OPTIONs from the first SELECT on the page, and then select the OPTION with the displayed text of “Edam”.
Once you’ve finished filling out the form, you probably want to submit it. One way to do this would be to find the “submit” button and click it:
driver.findElement(By.id("submit")).click();
Alternatively, WebDriver has the convenience method “submit” on every element. If you call this on an element within a form, WebDriver will walk up the DOM until it finds the enclosing form and then calls submit on that. If the element isn’t in a form, then the NoSuchElementException will be thrown:
element.submit();

No comments:

Post a Comment