选择->选项抽象
在Python,Java和其他几种硒绑定中,在select->option
HTML结构(Select
class)上有一个非常方便的抽象。
例如,假设有以下select
标记:
<select id="fruits" class="select" name="fruits">
<option value="1">Banana</option>
<option value="2">Mango</option>
</select>
这是我们如何在Python中操作它的方法:
from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_id('fruits'))
# get all options
print select.options
# get all selected options
print select.all_selected_options
# select an option by value
select.select_by_value('1')
# select by visible text
select.select_by_visible_text('Mango')
换句话说,这是一个 非常透明且易于使用的抽象 。
可以类似的方式 在量角器* 中操纵select
标签吗? *
-
在量角器中没有这样的东西,但是我们可以编写自己的东西:
select-wrapper.js
'use strict'; var SelectWrapper = function(selector) { this.webElement = element(selector); }; SelectWrapper.prototype.getOptions = function() { return this.webElement.all(by.tagName('option')); }; SelectWrapper.prototype.getSelectedOptions = function() { return this.webElement.all(by.css('option[selected="selected"]')); }; SelectWrapper.prototype.selectByValue = function(value) { return this.webElement.all(by.css('option[value="' + value + '"]')).click(); }; SelectWrapper.prototype.selectByPartialText = function(text) { return this.webElement.all(by.cssContainingText('option', text)).click(); }; SelectWrapper.prototype.selectByText = function(text) { return this.webElement.all(by.xpath('option[.="' + text + '"]')).click(); }; module.exports = SelectWrapper;
用法
var SelectWrapper = require('select-wrapper'); var mySelect = new SelectWrapper(by.id('fruits')); # select an option by value mySelect.selectByValue('1'); # select by visible text mySelect.selectByText('Mango');
请注意, Select
是JavaScript中的保留字