Selenium - Working with SELECT elements

来源:互联网 发布:淘宝号贷款怎么贷款 编辑:程序博客网 时间:2024/06/05 03:54

Select elements can require quite a bit of boiler plate code to automate. To reduce this and make your tests cleaner there is a Select class in the Selenium support package. To use it you will need the following import:

import org.openqa.selenium.support.ui.Select;
You are then able to create a Select object using a WebElement that references a <select> element.

WebElement selectElement = driver.findElement(By.id("selectElementID"));Select selectObject = new Select(selectElement);
The select object will now give you a series of commands that allow you to interact with a <select> element. First of all you have some options to select various options from the <select> element.

<select> <option value=value1>Bread</option> <option value=value2 selected>Milk</option> <option value=value3>Cheese</option></select>
To select the first option from the above element you now have three options:

// Select an <option> based upon the <select> elements internal indexselectObject.selectByIndex(1);// Select an <option> based upon its value attributeselectObject.selectByValue("value1");// Select an <option> based upon its textselectObject.selectByVisibleText("Bread");
You can then check which options are selected by using:

// Return a WebElement<List> of options that have been selectedList<WebElement> allSelectedOptions = selectObject.getAllSelectedOptions();// Return a WebElement referencing the first selection option found by walking down the DOMWebElement firstSelectedOption = selectObject.getFirstSelectedOption();
Or you may just be interested in what <option> elements the <select> element contains:

// Return a WebElement<List> of options that the <select> element containsList<WebElement> allAvailableOptions = selectObject.getOptions();
If you then want to deselect any elements you now have four options:

// Deselect an <option> based upon the <select> elements internal indexselectObject.deselectByIndex(1);// Deselect an <option> based upon its value attributeselectObject.deselectByValue("value1");// Deselect an <option> based upon its textselectObject.deselectByVisibleText("Bread");// Deselect all selected <option> elementsselectObject.deselectAll();

Finally, some <select> elements allow you to select more than one option, you can find out if your <select> element is one of these by using:

Boolean doesThisAllowMultipleSelections = selectObject.isMultiple();
1 0
原创粉丝点击