Selenium - Working with SELECT elements

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击人工智能教程

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 index
selectObject.selectByIndex(1);

// Select an <option> based upon its value attribute
selectObject.selectByValue("value1");

// Select an <option> based upon its text
selectObject.selectByVisibleText("Bread");

You can then check which options are selected by using:

// Return a WebElement<List> of options that have been selected
List<WebElement> allSelectedOptions = selectObject.getAllSelectedOptions();

// Return a WebElement referencing the first selection option found by walking down the DOM
WebElement 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 contains
List<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 index
selectObject.deselectByIndex(1);

// Deselect an <option> based upon its value attribute
selectObject.deselectByValue("value1");

// Deselect an <option> based upon its text
selectObject.deselectByVisibleText("Bread");

// Deselect all selected <option> elements
selectObject.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
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值