简体   繁体   中英

Find the selected radio button in a list of <label> using selenium webdriver

How to loop through all the label items in a div . I mean there are a bunch of unknown number of label tags which inturn have radio button. Using Selenium WebDriver . I need to find the selected radio button . There are two things here:

  1. I need to find the number of radio elements
  2. I need to find the selected radio element

For example

 <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> 

Here is what I've tried

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;
}

Instead of using xpath to find all radio buttons you can find it just simply using By.name which is much faster than xpath . Try as below :-

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();
    }
  }

Hope it helps...:)

//This will give the number of radio elements

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

// Iterate the above element and use isSelected() method to identify the selected radio elements

Hope this clarify

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM