Python - Selenium - Check radio buttons and checkboxes

By xngo on June 18, 2019

The Python code below shows you how to check radio buttons and checkboxes using different Selenium locators.

import time
 
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
 
# Create chrome driver.
driver = webdriver.Chrome()
 
# Open the webpage.
driver.get("https://openwritings.net/sites/default/files/selenium-test-pages/radio_checkbox.html")
 
# Pause for 5 seconds for you to see the initial state.
time.sleep(5)
 
# Radio Button: Check Monday using XPATH locator.
element = driver.find_element_by_xpath("//input[@value='Mon']")
element.click()
 
# Checkbox: Uncheck Apple using CSS selector.
element = driver.find_element_by_css_selector("input[name='apple']")
element.click()
 
# Checkbox: Check Orange using CSS selector.
element = driver.find_element_by_css_selector("input[name='orange']")
element.click()
 
# Pause for 10 seconds so that you can see the results.
time.sleep(10)
 
# Close.
driver.close()

Here is a video showing the code above in action.

Output of Selenium: Check radio button and checkboxes

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.