<label for="experience">Years of Experience:</label>
<input name="experience" type="radio" value="one" style="">
<input name="experience" type="radio" value="two">
<input name="experience" type="radio" value="three">
<input name="experience" type="radio" value="four">
<input name="experience" type="radio" value="above seven">

This does not give me a proper result.

WebElement val = driver.findElement(By.name("experience"));
List<WebElement>radios = val.findElements(By.xpath("//input[@type ='radio']"));

1 Answer 1


Let's analyze your code:

// The line below will find the first input. This line is useless
WebElement val = driver.findElement(By.name("experience"));
// Since val only contains the first input, radios will be an empty list
List<WebElement> radios = val.findElements(By.xpath("//input[@type ='radio']"));
// Below will raise an expection, because the list is empty

A suggestion:

// Finding all radios
List<WebElement> radios = driver.findElements(By.cssSelector("input[name='experience']"));
// Let's filter out only the checked radios. 
// In Selenium, isSelected will verify if it is checked
List<WebElement> checkedRadios = radios.stream().filter(radio -> radio.isSelected() ).collect(Collectors.toList());
// Let's check if we have found at least one checked radio button
Boolean hasCheckedRadio = !checkedRadios.isEmpty();

The code above necessarily walks through all radios. If you are worried about performance, you can wrap the code in a method and run a for loop which stops as soons as it finds a checked radio:

List<WebElement> radios = driver.findElements(By.cssSelector("input[name='experience']"));
for (WebElement radio : radios) {
    if(radio.isSelected()) return true;
return false;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.