在 Python、Java 和其他几个 selenium 绑定(bind)中,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')
换句话说,它是一个非常透明且易于使用的抽象。
是否有可能以类似的方式在 Protractor 中操作select
标签?
这不是 How to select option in drop down protractorjs e2e tests 的副本或 How to click on option in select box in Protractor test? .
最佳答案
Protractor 中没有这样的东西,但我们可以自己写:
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');
注意选择是一个reserved word in JavaScript
关于python - 选择 -> 选项抽象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28723419/