2014-03-03 19 views

回答

5

是的,这是可能的。假设我们有以下select元素:

<select name="test" id="select"> 
    <option value="1">1</option> 
    <option value="2">2</option> 
    <option value="3">3</option> 
</select> 

您使用getValue获取当前选定的选项,您可以使用click更改选择。这里有一个简单的例子:

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

希望有帮助。

欢呼

+0

我以为我想这样的产品......谢谢,这作品! – Offirmo

+1

+1但是,这是特定的框架,但这个想法是正确的,并帮助我走向正确的方向。对于那些对纯WebDriver解决方案感兴趣的人,请查看我的答案。 – nilesh

2

对于那些谁只是在寻找纯WebDriverJS的解决方案,而不是具体的像webdriver.io或量角器任何框架,这里是代码,

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

如果您想要的选项元素,使用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. 
    }); 
2

如果你有这个在你的HTML为例

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

为我过了例如选择3选择,我使用硒的webdriver用JavaScript

+0

请为此添加说明,以便其他人可以理解它的工作原理。谢谢。 – rsjaffe

+0

非常感谢!我尝试了其他一些方法来做到这一点,但这是唯一真正起作用的方法。 – Gennon

相关问题