[英]With webdriver.js, how to get the selected option of a <select>?
Plenty of answers for java and C#, but I can't find how to do it in javascript. 很多java和C#的答案,但我找不到如何在javascript中做到这一点。 Seems the API are different... 似乎API不同......
yeah it is possible. 是的,这是可能的。 Lets say we have the following select element: 假设我们有以下select元素:
<select name="test" id="select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
You get the current selected option by using getValue and you can change the selection by using click. 您可以使用getValue获取当前选定的选项,并可以使用单击更改选择。 Here is an simple example: 这是一个简单的例子:
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();
Hope that helps. 希望有所帮助。
cheers 干杯
For those who are just looking for pure WebDriverJS solution and not any framework specific like webdriver.io or protractor, here is the code, 对于那些只是寻找纯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');
}
});
If you want the option element, use the return value of then
callback: 如果你想要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.
});
If you have this in your html for an example 如果您在html中有这个例子
<select name="test" id="myId">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
You can select for a example option 3 like this 您可以选择这样的示例选项3
var driver = new firefox.Driver();
driver.findElement(By.css('#myId>option:nth-child(2)')).click();
Works for me and I am using selenium-webdriver with JavaScript 适合我和我使用selenium-webdriver与JavaScript
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.