简体   繁体   中英

Selecting dropdown in WebDriverJs

I have a dropdown box that I would like to select a value using WebDriverJS. I've looked at the user guide below and could not find out how to do it

https://code.google.com/p/selenium/wiki/WebDriverJs

I even try a few things that was documented for Java version like this:

webdriver.Select(driver.findElement(webdriver.By.id("vote"))).selectByValue("5")

And it just simply says that "Select" does not exist.

I went through the source and still cannot find anything that I can use.

You don't need two clicks to select an option, just click on the option directly. Something like,

driver.findElement(wd.By.css('#month>option[title=\'November\']')).click();

I shared a function to select a drop down item by it's text here .

The code:

function selectOption(selector, item){
    var selectList, desiredOption;

    selectList = this.findElement(selector);
    selectList.click();

    selectList.findElements(protractor.By.tagName('option'))
        .then(function findMatchingOption(options){
            options.some(function(option){
                option.getText().then(function doesOptionMatch(text){
                    if (item === text){
                        desiredOption = option;
                        return true;
                    }
                });
            });
        })
        .then(function clickOption(){
            if (desiredOption){
                desiredOption.click();
            }
        });
}

use with:

driver.selectOption = selectOption.bind(driver);
driver.selectOption(webdriver.By.id('my-dropdown'), 'My Value');
driver.findElement({id: 'myDropDown'});// select dropdown element you wish to select driver.sleep(1000);//not necessary driver.findElement({id: 'myDropDown'}).sendKeys('name_of_option');//sending keys automatically fills dropdown with desired option

我正在使用webdriverjs并希望按索引选择选项,所以这样做了:

driver.click('#my_select_box').click('#my_select_box option:nth-child(3)')

This should achieved by

selectElem = driver.findElement(webdriver.By.id("vote"))
selectElem.click()
selectElem.findElement(webdriver.By.css("option[value='5']")).click()

Sending keys to the dropdown element would be sufficient in this case, like;

driver.findElement(by.id('vote')).sendKeys('5');

When there is a space in the display text, webdriver needs to focus more so just adding click functions would solve it;

var ddlElement = driver.findElement(by.id('vote'));
ddlElement.click();
ddlElement.sendKeys('5');
ddlElement.click();

Certain browsers were being very difficult with dropdowns. I got some ideas and pieced together a java method using JS injection that might work for some of you who come across this. Yes, the issues are being fixed over time, but this is useful for those who are tasked with certifying older browsers. I hope this helps, because this can be very frustrating!

public void getJSDropdown(String dropDown, String elementID)throws Exception{

     JavascriptExecutor executor = (JavascriptExecutor)driver;
     String dropdownScript = "var select = window.document.getElementById('" + 
             dropDown +
             "'); for(var i = 0; i < select.options.length; i++){if(select.options[i].text == '" +
             elementID +
             "'){ select.options[i].selected = true; } }";

     Thread.sleep(2000);
     executor.executeScript(dropdownScript);
     Thread.sleep(2000);

     String clickScript = "if ("+"\"createEvent\""+" in document) {var evt = document.createEvent("+"\"HTMLEvents\""+");     evt.initEvent("+"\"change\""+", false, true); " + dropDown + ".dispatchEvent(evt); } else " + dropDown + ".fireEvent("+"\"onchange\""+");";

     executor.executeScript(clickScript);

 }

driver.click('//*[@id="vote"]/option[3]')

参考: https : //stackoverflow.com/a/22159563/227578

This will work for me (coffeescript)

selectList.findElements(By.tagName("option")) =
.then (options) ->
    len = options.length         #getting number of options in the select
    driver.wait =>               #verify all promises finished
        for option in options
            option.getText()
            .then (text) =>
                console.log(len)
                len -= 1
                console.log(text)
                if len is 0
                    true
    , 10000 

I was using the following with ES6:

 let select = driver.findElement(By.css("select"));
 let options = select.findElements(By.css("option"));
 options.then(values => {
     return Promise.all(values.map(el => el.getText())).then(optTexts => {
         return values[optTexts.indexOf('Some option text')].click();
     });
 });

像这样使用 xpath

await driver.findElement(By.xpath('//[@id="newEventOffices"]/option[3]')).click();

Find the select element and click on it to display the dropdown

driver.findElement(//div//select[@id="elementId"]).click();

Then select from the options and click on it. I think selecting by xpath will really work better here.

driver.findElement(By.xpath('//div//select[@id="elementId"]//option[optionIndex]')).click();

I get same problem, and above solutions not working in my typeScript case

But I still find a solution:

await driver.findElement(By.id("ELEMENT_ID")).sendKeys("SOME_VALUE");

Due to driver will return a promise when get a selector element

So add await to do the next things

The following code defines the available selectors in WebDriverJS:

webdriver.Locator.Strategy = {
  'className': webdriver.Locator.factory_('class name'),
  'class name': webdriver.Locator.factory_('class name'),
  'css': webdriver.Locator.factory_('css selector'),
  'id': webdriver.Locator.factory_('id'),
  'js': webdriver.Locator.factory_('js'),
  'linkText': webdriver.Locator.factory_('link text'),
  'link text': webdriver.Locator.factory_('link text'),
  'name': webdriver.Locator.factory_('name'),
  'partialLinkText': webdriver.Locator.factory_('partial link text'),
  'partial link text': webdriver.Locator.factory_('partial link text'),
  'tagName': webdriver.Locator.factory_('tag name'),
  'tag name': webdriver.Locator.factory_('tag name'),
  'xpath': webdriver.Locator.factory_('xpath')
};

goog.exportSymbol('By', webdriver.Locator.Strategy);

Source: https://code.google.com/p/selenium/source/browse/javascript/webdriver/locators.js

This is not actually clicking the option, but it does in fact select it.

  1. Find select element
  2. Click select element
  3. Type option text into select element using sendKeys()
  4. Click select element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM