How to Handle Radio Button in Selenium WebDriver?

I think radio button I’d is dynamically generated. Try using By.name() with WebDriverWait to wait until radio button visible.

Performing radio button select operation is quite easy if you want to select the radio button without checking if any of the button is selected by default.

In most of the cases, ID attribute of the radio button will serve purpose, since ID attribute will be different for each radio button. Note that, most of the time, name will be same for all radio buttons of specific field. So, if you wanted to use list & check if any of the button is selected, you can use name attribute.

Let us consider below example. –

As shown on above screen shot, there are 2 radio buttons, let us see, how can we select them.
Below is the HTML code for these radio buttons.

<div class="radio-inline">
<label class="top" for="id_gender1">
<div id="uniform-id_gender1" class="radio">
<span>
<input id="id_gender1" type="radio" value="1" name="id_gender">
</span>
</div>
Mr. 
</label>
</div>
<div class="radio-inline">
<label class="top" for="id_gender2">
</div>
</div>
So, as you can see, ID attribute for each radio button is different, we can use it for selection. Lets see how to do this.

                String gender = "female";
  WebElement RadioButtonMr = driver.findElement(By.xpath("//*[@id='id_gender1']"));
  WebElement RadioButtonMrs = driver.findElement(By.xpath("//*[@id='id_gender2']"));
  
  if (gender.equalsIgnoreCase("male")){
   RadioButtonMr.click();
  }
  if (gender.equalsIgnoreCase("Female")){
   RadioButtonMrs.click();
  }

Above code is a very simple approach how can we select radio button.

Another way to select the radio buttons is by using the value attribute.

 Let us see, how this can be achieved.

As we saw earlier, name attribute will be same for radio buttons. So, what we can do is, get the list of radio buttons by unique name and iterate on it.
String valueOfGender = "2"; //in this case, value is integer, it can be String in most of the cases. 
List<WebElement> RadioButtonList = driver.findElements(By.name("id_gender"));
  System.out.println("Total numer of Radio Buttons for gender field is: " +RadioButtonList.size());
  
  for (int i = 0; i < RadioButtonList.size(); i++){
   String gend = RadioButtonList.get(i).getAttribute("value");
   if (gend.equalsIgnoreCase((valueOfGender))){
    RadioButtonList.get(i).click();
    break;
   }
   
  }

Refer below post for complete example of Automation of Registration page using Selenium WebDriver.

Refer below video –

Hope this helps !!!