簡體   English   中英

使用webdriver.js,如何獲取a的選定選項 <select> ?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM