【问题标题】:Find the selected radio button in a list of <label> using selenium webdriver使用 selenium webdriver 在 <label> 列表中查找选定的单选按钮
【发布时间】:2016-11-16 12:12:12
【问题描述】:

如何遍历div 中的所有label 项目。我的意思是有一堆未知数量的标签标签,它们又具有单选按钮。使用 Selenium WebDriver。我需要找到选中的radio button。这里有两件事:

  1. 我需要找出单选元素的数量
  2. 我需要找到选中的单选元素

例如

<div class="controls">
	<label class="radio inline">
		<input type="radio" value="0" name="PlaceOfResidence"/>
	Urban           
	</label>
	<label class="radio inline">
		<input type="radio" value="1" name="PlaceOfResidence"/>
	Suburb           
	</label>
	<label class="radio inline">
		<input type="radio" value="2" name="PlaceOfResidence"/>
	Rural           
	</label>
	<label class="radio inline">
		<input type="radio" value="3" name="PlaceOfResidence"/>
	Not Available           
	</label>
</div>

这是我尝试过的

private String isRadioButtonSelected2(String name){
    List<WebElement> webEl = this.getWrappedDriver().findElements(By.xpath("//input[@type='radio' and @name = '"+name+"']/parent::label")); //and @value='"+value+"']"));
    String selectedValue = "";
    for(WebElement element: webEl){
        Boolean selectedRadio = element.isSelected();
        if(selectedRadio){
            selectedValue =this.getWrappedDriver().findElement(By.xpath("//input[@type='radio' and @name = '"+name+"']/parent::label")).getText();

            log("&&&&&&&&&&"+selectedValue);
        }else{
            return null;
        }
    }
    return selectedValue;
}

【问题讨论】:

    标签: java html selenium selenium-webdriver webdriver


    【解决方案1】:

    //这将给出单选元素的数量

    List<WebElement> radioButtons = driver.findElements(By.xpath("//input[type=radio]")); int size = = radioButtons.size();

    // 迭代上面的元素,使用isSelected()方法识别选中的单选元素

    希望澄清

    【讨论】:

    • 成功了!我迭代了大小并使用了 isSelected()
    【解决方案2】:

    您只需使用By.name 即可找到它,而不是使用xpath 来查找所有单选按钮,这比xpath 快得多。尝试如下:-

    List<WebElement> radioButtons = this.getWrappedDriver().findElements(By.name("PlaceOfResidence")); 
    int size = radioButtons.size();
    // This is the count of total radio button
    
    for(WebElement radio : radioButtons) 
     {
      If(radio.isSelected())
       {
         String  selectedValue =radio.findElement(By.xpath("./parent::label")).getText();
        }
      }
    

    希望对您有所帮助...:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-17
      • 2015-06-21
      • 1970-01-01
      • 1970-01-01
      • 2014-06-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多