Radio button interactions in Selenium Python - Build an Automation Script
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import unittest class PreferencesPage: def __init__(self, driver): self.driver = driver self.monthly_radio = (By.ID, 'subscription_monthly') self.yearly_radio = (By.ID, 'subscription_yearly') def select_monthly(self): WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable(self.monthly_radio) ).click() def select_yearly(self): WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable(self.yearly_radio) ).click() def is_monthly_selected(self): return self.driver.find_element(*self.monthly_radio).is_selected() def is_yearly_selected(self): return self.driver.find_element(*self.yearly_radio).is_selected() class TestRadioButtonSelection(unittest.TestCase): def setUp(self): self.driver = webdriver.Chrome() self.driver.get('http://example.com/preferences') self.page = PreferencesPage(self.driver) def tearDown(self): self.driver.quit() def test_radio_button_selection(self): # Select Monthly and verify self.page.select_monthly() self.assertTrue(self.page.is_monthly_selected(), "Monthly radio button should be selected") self.assertFalse(self.page.is_yearly_selected(), "Yearly radio button should not be selected when Monthly is selected") # Select Yearly and verify self.page.select_yearly() self.assertTrue(self.page.is_yearly_selected(), "Yearly radio button should be selected") self.assertFalse(self.page.is_monthly_selected(), "Monthly radio button should not be selected when Yearly is selected") if __name__ == '__main__': unittest.main()
This test script uses Selenium with Python and unittest framework.
The PreferencesPage class is a Page Object that holds locators and actions for the radio buttons. It uses By.ID locators for the 'Monthly' and 'Yearly' radio buttons, which is a best practice for stable selectors.
Explicit waits (WebDriverWait) ensure the radio buttons are clickable before clicking, avoiding flaky tests.
The test test_radio_button_selection selects 'Monthly' first and asserts it is selected while 'Yearly' is not. Then it selects 'Yearly' and asserts the opposite. This confirms only one radio button is selected at a time.
Assertions have clear messages to help understand failures.
The setUp and tearDown methods handle browser start and cleanup.
This structure keeps test logic clean and maintainable.
Now add data-driven testing with 3 different subscription types: 'Monthly', 'Yearly', and 'Weekly' (assume 'Weekly' radio button exists with ID 'subscription_weekly').