Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

python - Select -> option abstraction

In Python, Java and several other selenium bindings, there is a very convenient abstraction over select->option HTML constructions, a Select class.

For example, imagine there is the following select tag:

<select id="fruits" class="select" name="fruits">
    <option value="1">Banana</option>
    <option value="2">Mango</option>
</select>

Here is how we can operate it in 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')

In other words, it is a very transparent and easy to use abstraction.

Is is possible to manipulate select tag in protractor in a similar manner?


This is not a duplicate of How to select option in drop down protractorjs e2e tests or How to click on option in select box in Protractor test?.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No such thing in Protractor, but we can write our own:

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;


Usage

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');


Note that Select is a reserved word in JavaScript


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...