Java 如何在selenium webdriver的多选框中选择元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21421790/
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-08-13 08:38:47  来源:igfitidea点击:

how to select element in multi select box in selenium webdriver

javahtmlseleniumselenium-webdriver

提问by testing

Currently working on Selenium WebDriverand using Java.. I want to know to select values in Multi-selectbox. The options are already selected.. If i want to select any two or more option. how can perform the action.

目前正在使用Selenium WebDriver并使用Java.. 我想知道在选框中选择值。选项已被选中.. 如果我想选择任何两个或更多选项。如何执行操作。

The HTML is follows:

HTML如下:

<select id="swpacksId" multiple="" style="width: 125px; display: none;" name="swPacks[]">
<option selected="" value="ADVIP">ADVIP</option>
<option selected="" value="ADVLEG">ADVLEG</option>
<option selected="" value="ADVSEC">ADVSEC</option>
<option selected="" value="Boot">Boot</option>
<option selected="" value="H323">H323</option>
<option selected="" value="IBC">IBC</option>
<option selected="" value="MULTI">MULTI</option>
<option selected="" value="None">None</option>
</select>

enter image description here

在此处输入图片说明

采纳答案by Ships

In a function pass a list of values use any delimiter lets say comma as a delimiter:

在函数传递值列表中使用任何分隔符可以说逗号作为分隔符:

public static void selectMultipelValues(String multipleVals) {
   String multipleSel[] = multipleVals.split(",");

   for (String valueToBeSelected : multipleSel) {
      new Select(driver.findElement(By.id(propId))).selectByVisibleText(valueToBeSelected);
      driver.findElement(By.id(ddObj)).sendKeys(Keys.CONTROL);
   }
}

回答by A Paul

Please check if below url helps you

请检查以下网址是否对您有帮助

http://selenium.polteq.com/en/controlling-a-selectbox-or-dropdownbox-with-selenium-webdriver/

http://selenium.polteq.com/en/controlling-a-selectbox-or-dropdownbox-with-selenium-webdriver/

You can check below option

您可以检查以下选项

public void selectByValue() { 
     Select selectBox = 
           new Select(driver.findElement(By .cssSelector("select#id_contact")));       
     selectBox.selectByValue("2"); 
}

public void selectByIndex() {  
     Select selectBox = 
           new Select(driver.findElement(By.cssSelector("select#id_contact"))); 
     selectBox.selectByIndex(2); 
}

you can change it according to your requirement

你可以根据你的要求改变它

回答by testing

I have written code like this.. 1st i deselected all the values in the multi select box then i selected the values which i want.. It is working properly..

我已经写了这样的代码.. 1st 我取消选择多选框中的所有值然后我选择了我想要的值..它工作正常..

Log.info("Clicking on Softwarepack dropdown");
JavascriptExecutor executor31 = (JavascriptExecutor)driver;
executor31.executeScript("document.getElementById('swpacksId').style.display='block';");
Select select31 = new Select(driver.findElement(By.id("swpacksId")));
select31.deselectAll();
select31.selectByVisibleText("ADVLEG");
Thread.sleep(6000);
JavascriptExecutor executor32 = (JavascriptExecutor)driver;
executor32.executeScript("document.getElementById('swpacksId').style.display='block';");
Select select32 = new Select(driver.findElement(By.id("swpacksId")));
select32.selectByVisibleText("SIP");

回答by Ant's

If you have Utilsstatic method like this:

如果你有这样的Utils静态方法:

public static void selectTheDropDownList(WebElement dropDown,String text)
{
    Select select = new Select(dropDown);
    select.selectByVisibleText(text);       
}

and you can do like this, to select multiple options:

你可以这样做,选择多个选项:

Utils.selectTheDropDownList(dropDown,text1);
Utils.selectTheDropDownList(dropDown,text2);
. . . 
Utils.selectTheDropDownList(dropDown,textn);

This should work.

这应该有效。

回答by Vishal

new Select(driver.findElementByXPath("XXXXXXXXXXX"))).selectByIndex(2);

回答by Andrzej

You need to click element with control. Here is documentation how to make such action https://code.google.com/p/selenium/wiki/AdvancedUserInteractions

您需要使用控件单击元素。这是如何进行此类操作的文档 https://code.google.com/p/selenium/wiki/AdvancedUserInteractions

In our case it could be:

在我们的例子中,它可能是:

Select select = new Select(element);

Actions builder = new Actions(driver);
builder.keyDown(Keys.CONTROL)
.click(select.getOptions().get(2))
.keyUp(Keys.CONTROL);

builder.build().perform();

回答by Dnyaneshwar Raut

For multiple section you can do:

对于多个部分,您可以执行以下操作:

Select select = new Select(element);
Actions builder = new Actions(driver);
builder.keyDown(Keys.CONTROL)
.click(select.getOptions().get(2))
.click(select.getOptions().get(3))
.click(select.getOptions().get(4))
.keyUp(Keys.CONTROL);

builder.build().perform();

回答by S. Yanusheuski

This works for me:

这对我有用:

final String[] textOptions = {"value1", "value2"};
final WebElement element = driver.findElement(By.id("someId"));
final Select dropdown = new Select(element);
final List<WebElement> options = dropdown.getOptions();
final Actions builder = new Actions(driver);
final boolean isMultiple = dropdown.isMultiple();
if (isMultiple) {
    dropdown.deselectAll();
}
builder.keyDown(Keys.CONTROL);
for (String textOption : textOptions) {
    for (WebElement option : options) {
        final String optionText = option.getText().trim();
        if (optionText.equalsIgnoreCase(textOption)) {
            if (isMultiple) {
                if (!option.isSelected()) {
                    builder.click(option);
                }
            } else {
                option.click();
            }
            break;
        }
    }
}
builder.keyUp(Keys.CONTROL).build().perform();

回答by ThugMeister22

Use the below code, its simple and easy!! It worked for me.

使用下面的代码,简单易行!!它对我有用。

Select dd1 = new Select(driver.findElement(By.name("swPacks[]")));
dd1.selectByVisibleText("ADVIP");
dd1.selectByVisibleText("ADVLEG");

回答by Nikita Lobach-Zhuchenko

I have spent quite some time trying to simulate a click with the control key pressed with the webdriver for Chrome. After some investigation it appeared, that when you generate a click on an OPTION element of a multiselect, no click actually happens. Instead, a change event is genetared in the browser. This leads to the situation, where subsequent "clicks" on other options of the multiselect do not clear the previously selected options, which is sometimes unwanted behavior. To solve this I have come up with the following solution:

我花了相当多的时间来尝试使用 Chrome 的 webdriver 按下控制键来模拟点击。经过一些调查后发现,当您单击多选的 OPTION 元素时,实际上并没有发生单击。相反,更改事件在浏览器中生成。这会导致这种情况,即后续“单击”多选的其他选项不会清除先前选择的选项,这有时是不需要的行为。为了解决这个问题,我想出了以下解决方案:

Actions actions = new Actions(driver);
if(controlNeeded)
    actions.keyDown(Keys.CONTROL);
actions.moveToElement((WebElement) option_you_want_to_click);
actions.clickAndHold();
actions.pause(100);
actions.release();
if(controlNeeded)
    actions.keyUp(Keys.CONTROL);
actions.build().perform();

This way you can select both single and multiple elements depending on the Ctrl key.

通过这种方式,您可以根据 Ctrl 键选择单个和多个元素。