[英]With webdriver.js, how to get the selected option of a <select>?
很多java和C#的答案,但我找不到如何在javascript中做到这一点。 似乎API不同......
是的,这是可能的。 假设我们有以下select元素:
<select name="test" id="select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
您可以使用getValue获取当前选定的选项,并可以使用单击更改选择。 这是一个简单的例子:
var webdriverjs = require('webdriverjs'),
client = webdriverjs.remote({desiredCapabilities:{browserName:'phantomjs'}}).init();
client
.url('http://localhost:8080')
.getValue('#select',function(err,val){
console.log(val); // will output "1"
})
.click('//*[@id="select"]/option[3]')
.getValue('#select',function(err,val){
console.log(val); // will output "3"
})
.end();
希望有所帮助。
干杯
对于那些只是寻找纯WebDriverJS解决方案的人而不是像webdriver.io或protractor这样的任何特定框架,这里是代码,
var element = driver.findElement(wd.By.id('mySelect'));
element.getAttribute('value').then(function(selected) {
if(selected === 'the one I expected') {
done();
}
else {
done(new Error('something went wrong');
}
});
如果你想要option元素,请使用then
callback的返回值:
driver.findElement(By.css('select[name=eventTypes]'))
.then((select) => {
return select.getAttribute('value').then((value) => {
return {select: select, value: value};
});
})
.then((data) => {
return data.select.findElement(By.css('option[value="'+data.value+'"]'));
})
.then((option) => {
//do something.
});
如果您在html中有这个例子
<select name="test" id="myId">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
您可以选择这样的示例选项3
var driver = new firefox.Driver();
driver.findElement(By.css('#myId>option:nth-child(2)')).click();
适合我和我使用selenium-webdriver与JavaScript
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.