如何使用Selenium WebDriver(Selenium 2)从组合框中获取所选值?

时间:2012-08-16 16:54:33

标签: selenium-webdriver

假设我有这个HTML代码:

<select id="superior" size="1" name="superior">
    <option value=""></option>
    <option value="c.i.e.m.md.Division_1">DIVISION007</option>
    <option selected="selected" value="c.i.e.m.md.Division_$$_javassist_162_119">MyDivision</option>
    <option value="c.i.e.m.md.Division_121">MyDivision4</option>
    <option value="c.i.e.m.md.Division_122">MyDivision5</option>
</select>

所以这是一个带

的组合框
id=superior 

并且当前选择了MyDivision值。

使用Selenium WebDriver我试图获取所选值,但没有成功。

我试过了:

String option = this.ebtamTester.firefox.findElement(By.id(superiorId)).getText();
return option;

但这会返回组合框中的所有值。

请帮忙吗?

编辑:

WebElement comboBox = ebtamTester.firefox.findElement(By.id("superior"));
SelectElement selectedValue = new SelectElement(comboBox);
String wantedText = selectedValue.getValue();

5 个答案:

答案 0 :(得分:15)

这是用C#编写的,但要将其转换为您正在使用的任何其他语言并不难:

IWebElement comboBox = driver.FindElement(By.Id("superior"));
SelectElement selectedValue = new SelectElement(comboBox);
string wantedText = selectedValue.SelectedOption.Text;

SelectElement要求您使用OpenQA.Selenium.Support.UI,因此在顶部键入

using OpenQA.Selenium.Support.UI;

编辑:

我想你,而不是'司机',你会使用

IWebElement comboBox = this.ebtamTester.firefox.FindElement(By.Id("superior"));

答案 1 :(得分:9)

在Java中,以下代码应该可以正常工作:

import org.openqa.selenium.support.ui.Select;
Select comboBox = new Select(driver.findElement(By.id("superior")));
String selectedComboValue = comboBox.getFirstSelectedOption().getText();
System.out.println("Selected combo value: " + selectedComboValue);

当前选择MyDivision时,上面的代码将打印“MyDivision”

答案 2 :(得分:4)

  

selectedValue.SelectedOption.Text;会得到你的文字   选定的项目。有谁知道如何获得所选的值。

要获取所选值,请使用

selectedValue.SelectedOption.GetAttribute("value");

答案 3 :(得分:3)

根据标签选择选项:

Select select = new Select(driver.findElement(By.xpath("//path_to_drop_down")));
select.deselectAll();
select.selectByVisibleText("Value1");

获取第一个选定值:

WebElement option = select.getFirstSelectedOption()

答案 4 :(得分:3)

在c#中使用XPath

  string selectedValue=driver.FindElement(By.Id("superior")).FindElements(By.XPath("./option[@selected]"))[0].Text;
相关问题