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):
service = Service(driver_path)
self.driver = webdriver.Chrome(service=service)
def navigate_to_url(self, 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:
radio_button = self.driver.find_element(
By.XPATH, f"//input[@id='{value}']")
radio_button.click()
if radio_button.is_selected():
print(f"The radio button with value '{value}' is selected.")
self.take_screenshot(f"{value}_button_selected")
else:
print(
f"Failed to select the radio button with value '{value}'.")
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."""
screenshot_directory = 'screenshots'
if not os.path.exists(screenshot_directory):
os.makedirs(screenshot_directory)
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__":
driver_path = 'D:/testtools/chromedriver.exe'
test = RadioButtonTest('D:/testtools/chromedriver.exe')
test.navigate_to_url('https://practice.expandtesting.com/radio-buttons')
test.select_radio_button('Black')
test.close_browser()