Skip to main content

Radio Button

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from selenium.common.exceptions import NoSuchElementException, WebDriverException
from datetime import datetime
import os


class RadioButtonTest:
def __init__(self, driver_path):
# Initialize the WebDriver.
service = Service(driver_path)
self.driver = webdriver.Chrome(service=service)

def navigate_to_url(self, url):
# """Navigate to a specified URL."""
try:
self.driver.get(url)
except WebDriverException:
print("Web page not accessible or URL is incorrect.")
self.take_screenshot("navigation_failed")
self.close_browser()
exit()

def select_radio_button(self, value):
"""Select radio button with specified value."""
try:
# Locate the radio button and click it
radio_button = self.driver.find_element(
By.XPATH, f"//input[@id='{value}']")
radio_button.click()

# Verify and print the selection status
if radio_button.is_selected():
print(f"The radio button with value '{value}' is selected.")
# Dynamic screenshot with action and outcome
self.take_screenshot(f"{value}_button_selected")
else:
print(
f"Failed to select the radio button with value '{value}'.")
# Dynamic screenshot with action and outcome
self.take_screenshot(f"{value}_button_selection_failed")
except NoSuchElementException:
print("Radio button not found on the web page.")
self.take_screenshot("radio_button_not_found")
self.close_browser()
exit()

def take_screenshot(self, name):
"""Take a full page screenshot with a dynamic name."""
# Define a dynamic path for screenshots
screenshot_directory = 'screenshots'
if not os.path.exists(screenshot_directory):
os.makedirs(screenshot_directory)

# Define the screenshot filename dynamically based on the name and timestamp
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"{screenshot_directory}/{name}_{timestamp}.png"
self.driver.save_screenshot(filename)
print(f"Screenshot saved as {filename}")

def close_browser(self):
"""Close the browser."""
self.driver.quit()


if __name__ == "__main__":
# Replace with your actual WebDriver path
driver_path = 'D:/testtools/chromedriver.exe'

# Test Case and Scenario Numbers (Incorporate as needed)
# TEST_CASE_NUMBER = "TC001"
# TEST_SCENARIO_NUMBER = "TS001"

# Initialize the test
test = RadioButtonTest('D:/testtools/chromedriver.exe')

# Navigate to the URL
test.navigate_to_url('https://practice.expandtesting.com/radio-buttons')

# Select the 'Black' radio button
test.select_radio_button('Black')

# Close the browser after the test
test.close_browser()