Handling Checkboxes and Radio Buttons in Selenium
Handling Checkboxes and Radio Buttons in Selenium
✅ 1. Setup Requirements
Install Selenium if you haven’t already:
bash
Copy
Edit
pip install selenium
✅ 2. Sample HTML for Practice (Example)
html
Copy
Edit
<input type="checkbox" id="subscribe" name="subscribe" value="newsletter">
<label for="subscribe">Subscribe to newsletter</label>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label>
✅ 3. Python Selenium Code
python
Copy
Edit
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
# Start the browser
driver = webdriver.Chrome()
# Load a sample web page (use your own local or test URL)
driver.get("https://example.com/form") # Replace with the actual URL
# Wait for elements to load (optional)
time.sleep(2)
# --------- Handling Checkbox ---------
checkbox = driver.find_element(By.ID, "subscribe")
# Select the checkbox if it's not already selected
if not checkbox.is_selected():
checkbox.click()
print("✅ Checkbox selected.")
else:
print("ℹ️ Checkbox was already selected.")
# --------- Handling Radio Buttons ---------
radio_male = driver.find_element(By.ID, "male")
radio_female = driver.find_element(By.ID, "female")
# Select a radio button
radio_female.click()
print("✅ Female radio button selected.")
# Check if a radio button is selected
if radio_female.is_selected():
print("🔎 Female is selected.")
else:
print("⚠️ Female is not selected.")
# Close the browser
driver.quit()
🔍 Explanation:
is_selected() checks whether a checkbox or radio button is selected.
.click() toggles the state (for checkboxes) or selects (for radio buttons).
Ensure you use the correct element locators (By.ID, By.NAME, etc.).
Learn Selenium JAVA Course in Hyderabad
Read More
How to Verify Page Title and URL with Selenium
Navigating Between Pages Using Selenium WebDriver
Visit Our IHUB Talent Training in Hyderabad
Comments
Post a Comment