How to Handle Radio Button in Selenium?

How to Handle Radio Button in Selenium?

Hi Rebecca,

To handle radio buttons in Selenium, you can use the WebElement class’s click() method to select a radio button. First, locate the radio button element using one of Selenium’s locator strategies such as ID, name, XPath, or CSS selector. Once the radio button element is located, use the click() method to simulate a click action on the radio button, thereby selecting it. Unlike checkboxes, radio buttons allow only one option to be selected from a group of options, so ensure that only one radio button is selected at a time within the group. Additionally, you can use assertions to verify the state of the radio button, such as checking if it is displayed, enabled, or selected, using methods like isSelected(), isEnabled(), and isDisplayed(). Handling radio buttons effectively in Selenium is crucial for accurately testing web applications with radio button input fields.

Please go through this blog to learn more:

To handle radio buttons in Selenium WebDriver, you can use the By.cssSelector method to locate the radio button element by its value attribute and then use the click() method to select it.

WebElement radioButton = driver.findElement(By.cssSelector("input[type='radio'][value='option1']"));
radioButton.click();

Another way to handle radio buttons is by using XPath. You can locate the radio button element using its XPath expression and then use the click() method to select it.

WebElement radioButton = driver.findElement(By.xpath(“//input[@type=‘radio’ and @value=‘option1’]”)); radioButton.click();