如何在Selenium 2中选择/获取下拉选项

96

我正在将我的Selenium 1代码转换为Selenium 2,但找不到任何简单的方法来选择下拉菜单中的标签或获取下拉菜单的选定值。您知道如何在Selenium 2中实现吗?

这里有两个可以在Selenium 1中工作但在Selenium 2中不起作用的语句:

browser.select("//path_to_drop_down", "Value1");
browser.getSelectedValue("//path_to_drop_down");

你尝试使用Firebug定位了吗?使用Firebug/xpather生成的xpath可以使定位更容易。 - user766038
1
问题不在于找到下拉框,而是选择其中的标签。我能够定位到下拉框,但不知道在Selenium 2中调用哪种方法,因为select()和getSelectedValue()或getSelectedLabel()在Selenium 2中无法使用。 - user786045
C#的解决方案:https://dev59.com/t2435IYBdhLWcg3wrSFB - steve cook
10个回答

184
请看Selenium文档中有关使用WebDriver填写表单的章节以及Select类的javadoc。将内容翻译为通俗易懂的语言,保留""和""和HTML标签。要选择基于标签的选项:
Select select = new Select(driver.findElement(By.xpath("//path_to_drop_down")));
select.deselectAll();
select.selectByVisibleText("Value1");

获取第一个选定的值:

WebElement option = select.getFirstSelectedOption()

By.xpath("//path_to_drop_down")。我会将其替换为像By.name这样的定位器。 - Daniel
2
如果选择不支持多选,则deselectAll会抛出UnsupportedOperationException异常。 - Tom Hartwell
4
在C#中使用SelectElement类,如下所示:SelectElement salesExecutiveDropDown = new SelectElement(webDriver.FindElement(By.Id("salesExecutiveId"))); - Jeremy McGee
该代码无法选择下拉菜单,直到我将此行注释掉://select.deselectAll(); 然后它开始工作。您的情况可能会有所不同。 - HRVHackers
1
请注意,deselectAll 方法仅适用于多选下拉框:https://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/support/ui/Select.html#deselectAll()。 - user1205577
是的,我会删除select.deselectAll()这一行代码,因为它对于大多数下拉菜单都不起作用,因为它们通常只能进行单选。 - kiedysktos

5
driver.findElement(By.id("id_dropdown_menu")).click();
driver.findElement(By.xpath("xpath_from_seleniumIDE")).click();

4

在 Ruby 中,如果需要常量,可以添加如下内容:

module Selenium
  module WebDriver
    class Element
      def select(value)
        self.find_elements(:tag_name => "option").find do |option|
          if option.text == value
            option.click
              return
           end
       end
    end
  end
end

你将能够选择一个值:

browser.find_element(:xpath, ".//xpath").select("Value")

3

请尝试使用以下方法:

selenium.select("id=items","label=engineering")

或者

selenium.select("id=items","index=3")

0

这个方法将返回下拉列表中的选择值,

public static String getSelected_visibleText(WebDriver driver, String elementType, String value)
  {
    WebElement element = Webelement_Finder.webElement_Finder(driver, elementType, value);
   Select Selector = new Select(element);
    Selector.getFirstSelectedOption();
    String textval=Selector.getFirstSelectedOption().getText();
    return textval;
  }

同时

String textval = Selector.getFirstSelectedOption();

element.getText();

将返回下拉列表中的所有元素。


0
使用Selenium中Select类的方法选择下拉列表中的特定值 Select类实现了select标签,提供了选择和取消选择选项的辅助方法。
WebElement dropdownlist = driver.findElement(By.xpath(locator));
Select listbox = new Select(dropdownlist);

使用select类的方法及示例:

selectByIndex(int index): Select the option at the given index.
listbox.selectByIndex(2);

selectByVisibleText(java.lang.String text): Select all options that display text matching the argument
listbox.selectByVisibleText(“Date”);

请参考下面的链接以获取更详细的讨论 这里

0

你可以这样做:

public void selectDropDownValue(String ValueToSelect) 
{

    webelement findDropDownValue=driver.findElements(By.id("id1"))    //this will find that dropdown 

    wait.until(ExpectedConditions.visibilityOf(findDropDownValue));    // wait till that dropdown appear

    super.highlightElement(findDropDownValue);   // highlight that dropdown     

    new Select(findDropDownValue).selectByValue(ValueToSelect);    //select that option which u had passed as argument
}

0
一个类似于janderson上面发布的选项是在Selenium 2中使用.GetAttribute方法。使用此方法,您可以获取任何具有特定值或标签的项目。这可用于确定元素是否具有标签、样式、值等。通常的做法是循环遍历下拉列表中的项目,直到找到所需的项目并选择它。在C#中实现。
int items = driver.FindElement(By.XPath("//path_to_drop_Down")).Count(); 
for(int i = 1; i <= items; i++)
{
    string value = driver.FindElement(By.XPath("//path_to_drop_Down/option["+i+"]")).GetAttribute("Value1");
    if(value.Conatains("Label_I_am_Looking_for"))
    {
        driver.FindElement(By.XPath("//path_to_drop_Down/option["+i+"]")).Click(); 
        //Clicked on the index of the that has your label / value
    }
}

0

Selenium WebDriver中的“Select”类用于选择和取消选择下拉列表中的选项。可以通过将下拉列表的webElement作为参数传递给其构造函数来初始化Select类型的对象。

WebElement testDropDown = driver.findElement(By.id("testingDropdown")); Select dropdown = new Select(testDropDown);

从下拉列表中选择选项

有三种从下拉列表中选择选项的方法-

  1. selectByIndex - 根据索引选择选项,从0开始。

dropdown.selectByIndex(3);

- 根据其“value”属性选择选项。

dropdown.selectByValue("Database");

  1. selectByVisibleText - 根据选项上的文本选择选项。

dropdown.selectByVisibleText("数据库测试");


-2

这是从下拉框中选择值的代码

selectlocator 的值将是下拉框的 xpath 或名称,optionLocator 将有要从下拉框中选择的值。

public static boolean select(final String selectLocator,
        final String optionLocator) {
    try {
        element(selectLocator).clear();
        element(selectLocator).sendKeys(Keys.PAGE_UP);
        for (int k = 0; k <= new Select(element(selectLocator))
                .getOptions().size() - 1; k++) {
            combo1.add(element(selectLocator).getValue());
            element(selectLocator).sendKeys(Keys.ARROW_DOWN);
        }
        if (combo1.contains(optionLocator)) {
            element(selectLocator).clear();
            new Select(element(selectLocator)).selectByValue(optionLocator);
            combocheck = element(selectLocator).getValue();
            combo = "";

            return true;
        } else {
            element(selectLocator).clear();
            combo = "The Value " + optionLocator
                    + " Does Not Exist In The Combobox";
            return false;
        }
    } catch (Exception e) {
        e.printStackTrace();
        errorcontrol.add(e.getMessage());
        return false;
    }
}



private static RenderedWebElement element(final String locator) {
    try {

        return (RenderedWebElement) drivers.findElement(by(locator));
    } catch (Exception e) {
        errorcontrol.add(e.getMessage());
        return (RenderedWebElement) drivers.findElement(by(locator));
    }
}

谢谢,

Rekha。


4
过于复杂且使用已废弃的方法(RenderedWebElement) - Ardesco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接