2016-07-13 53 views
0

如何遍歷div中的所有label項。我的意思是有一堆未知數量的標籤標籤,其中有單選按鈕。使用Selenium WebDriver。我需要找到所選的radio button。這裏有兩件事情:使用硒webdriver在<label>列表中找到所選的單選按鈕

  1. 我需要找到無線電元件的數量
  2. 我需要找到所選擇的無線電元件

例如

<div class="controls"> 
 
\t <label class="radio inline"> 
 
\t \t <input type="radio" value="0" name="PlaceOfResidence"/> 
 
\t Urban   
 
\t </label> 
 
\t <label class="radio inline"> 
 
\t \t <input type="radio" value="1" name="PlaceOfResidence"/> 
 
\t Suburb   
 
\t </label> 
 
\t <label class="radio inline"> 
 
\t \t <input type="radio" value="2" name="PlaceOfResidence"/> 
 
\t Rural   
 
\t </label> 
 
\t <label class="radio inline"> 
 
\t \t <input type="radio" value="3" name="PlaceOfResidence"/> 
 
\t Not Available   
 
\t </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; 
} 

回答

2

而不是使用xpath找到所有的單選按鈕,你只需使用By.name,它比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(); 
    } 
    } 

希望它能幫助... :)

1

//這會給

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

//迭代以上元素,並使用isSelected()方法,以確定所選擇的無線電元件

希望這澄清

無線電元件的數目
+0

這工作!我迭代了大小,並使用isSelected() – shockwave

相關問題