Handling Radio Buttons in Selenium WebDriver: Automating Radio Button Selection
Learn how to automate radio button selection in Selenium WebDriver using Java. This tutorial provides code examples demonstrating how to locate radio buttons using different locator strategies, select specific options, and handle groups of radio buttons in your automated tests.
Handling Radio Buttons in Selenium WebDriver
Introduction to Radio Button Handling
Radio buttons are input elements where only one option from a group can be selected at a time. Automating radio button selection in Selenium involves locating the radio button element and using the `click()` method to select it. This tutorial demonstrates two approaches: direct selection using a locator and dynamic selection based on the index of the radio button within a group. We will use Java with Selenium. (Make sure you have Selenium and ChromeDriver properly installed.)
Locating Radio Buttons
Before you can select a radio button, you must locate it using a Selenium locator strategy (ID, name, XPath, CSS, etc.). Inspect the HTML of your page to find the best way to uniquely identify the radio button. Radio buttons are typically grouped using a shared 'name' attribute.
Methods for Handling Radio Buttons
isSelected()
: Checks if a radio button is currently selected. Returnstrue
if selected,false
otherwise.click()
: Selects the radio button. Only one radio button within a group can be selected at any one time.
Example 1: Direct Selection using XPath
Let's assume you have a simple HTML file (replace with your actual HTML) containing radio buttons:
<form>
<input type="radio" name="fruit" value="apple"/> Apple <br>
<input type="radio" name="fruit" value="banana"/> Banana <br>
<input type="radio" name="fruit" value="orange"/> Orange
</form>
To select the "Banana" radio button (assuming you have a variable `driver` that represents your webdriver), you'd use its value attribute:
driver.findElement(By.xpath("//input[@value='banana']")).click();
Example 2: Dynamic Selection Using Index
This approach is useful when you don't know the exact value of a radio button but know its position within a group. It assumes that the radio buttons share the same `name` attribute. In this example, let's select the second radio button of a group whose name is 'fruit':
List<WebElement> radioButtons = driver.findElements(By.name("fruit"));
int numberOfRadioButtons = radioButtons.size();
System.out.println("Number of radio buttons: " + numberOfRadioButtons);
// Select the second radio button (index 1)
radioButtons.get(1).click();
Number of radio buttons: 3