对于Java和C#有很多答案,但我找不到如何在JavaScript中实现。似乎API是不同的...
对于Java和C#有很多答案,但我找不到如何在JavaScript中实现。似乎API是不同的...
是的,这是可能的。假设我们有以下选择元素:
<select name="test" id="select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
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');
}
});
then
回调函数的返回值: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.
});
<select name="test" id="myId">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
var driver = new firefox.Driver();
driver.findElement(By.css('#myId>option:nth-child(2)')).click();
这对我来说很有效,我正在使用JavaScript的selenium-webdriver。
我用了这个
element=await driver.findElement(By.name("quantity")); // here you have to select your element suppose i am using get element by name
// below will help you to get selected value from select option
var SelectedValue=element.getAttribute('value').then(function(selected) { return selected;});
虽然这个问题已经发布了7年,但我想分享一下我的答案,它现在仍然有效。您可以通过以下方式获取所选选项/值
let select_value = await driver.findElement(By.css('select')).getAttribute('value')