Selenium选择器获取单选按钮文本

时间:2012-08-01 08:54:43

标签: java radio-button selenium-webdriver

我的标记类似于下面的标记。

<div id="food-group">
    <input type="radio" name="food" value="Milk"> Cow-Milk<br>
    <input type="radio" name="food" value="Butter" checked> Butter<br>
    <input type="radio" name="food" value="Cheese"> Cheddar-Cheese
<div>

我需要在每次输入(Cow-Milk,Cheddar-Cheese)之后使用Java中的Selenium WebDriver获取标签。 我可以像这样得到组件(并迭代它们):

driver.findElements(By.xpath([//div[@id='food-group']/input[@type='radio')).

但我无法找到获取文字的方法。

2 个答案:

答案 0 :(得分:0)

输入元素有两种类型的“text”属性。在您的示例中:

 <input type="radio" name="food" value="Milk"> Cow-Milk<br>

得到“牛奶”,你会这样做:

getAttribute("value");

得到“牛奶”,你会这样做:

getText();

答案 1 :(得分:0)

You can use 

    List<WebElements> myElements = driver.findElements(By.xpath([//div[@id='food-group']/input));

for(WebElement e : myElements) {
        String textValue = e.getAttribute("value");
        if(textValue.equals("Milk"){
          return el.getText();
        }
        else if(textValue.equals("Butter") {
          return el.getText();
        }
        else if(textValue.equals("Cheese") {
          return el.getText();
        }
    }