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:
WebElementselect=driver.findElement(By.tagName("select"));List<WebElement>allOptions=select.findElements(By.tagName("option"));for(WebElementoption: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.
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:
No comments:
Post a Comment