javascript 在 WebDriverJs 中选择下拉菜单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15859143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:21:09  来源:igfitidea点击:

Selecting dropdown in WebDriverJs

javascriptwebdriverselenium-webdriver

提问by vpn

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

我有一个下拉框,我想使用 WebDriverJS 选择一个值。我查看了下面的用户指南,但不知道如何操作

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

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

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

我什至尝试了一些为 Java 版本记录的内容,如下所示:

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.

我浏览了源代码,但仍然找不到任何可以使用的东西。

回答by nilesh

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

回答by Dan

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

回答by Beston Mawarire

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

回答by apfrod

I am using webdriverjsand want to select the option by index, so did:

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

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

回答by olcay

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;

当显示文本有空格时,webdriver需要更加关注,添加点击功能即可解决;

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

回答by Josheek

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!

某些浏览器很难使用下拉菜单。我得到了一些想法,并使用 JS 注入拼凑了一个 Java 方法,这可能对遇到此问题的一些人有用。是的,这些问题会随着时间的推移而得到解决,但这对于那些负责认证旧浏览器的人来说很有用。我希望这会有所帮助,因为这可能非常令人沮丧!

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

 }

回答by Pitsanu Swangpheaw

This should achieved by

这应该通过

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

回答by jonasnas

I was using the following with ES6:

我在 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();
     });
 });

回答by dule

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

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

Ref: https://stackoverflow.com/a/22159563/227578

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

回答by lucio bosque

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