Handling Check Boxes and Radio Buttons in Selenium WebDriver


Radio Buttons:
Radio Buttons can be toggled on by using the click() method.
below is the html content for radio buttons.

Scenario:
Open Chrome browser
Navigate to the https://facebook.com/ application
Select ‘Male’ option from Gender Section.
Note: you can use value or Id. 

Script:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
import time
chromePath=
"C:\\BrowserDrivers\\chromedriver.exe"
driver=webdriver.Chrome(executable_path=chromePath)
driver.get("https://facebook.com/") 
#Select the option Male.We will locate the Male radio button by inspecting its HTML codes.
driver.find_element_by_xpath("//input[@type='radio' and @value='2']").click() 

CheckBox :
Toggling a check box on/off is also done using the click() method.

Scenario 1:
Open Chrome browser.
Navigate to the https://www.spicejet.com/ application.
Select ‘Student’ check box. 
below is the html content for Student Check Box. 
Script: 
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
import time
chromePath=
"C:\\BrowserDrivers\\chromedriver.exe"
driver=webdriver.Chrome(executable_path=chromePath)
driver.get("https://www.spiceject.com/") 
#Select the Student check box .We will locate the Student by inspecting its HTML codes. 
driver.find_element_by_xpath("//input[@id='ctl00_mainContent_chk_StudentDiscount'] ").click()

Scenario 2:
Open Chrome browser.
Navigate to the https://mail.rediff.com/ application.
Click on Sign in.
Select “Keep me signed in” check box if it is not checked else not select.
(isSelected() method is used to know whether the Checkbox is selected or not)

Script: 
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
import time
chromePath=
"C:\\BrowserDrivers\\chromedriver.exe"
driver=webdriver.Chrome(executable_path=chromePath)
driver.get("https://www.rediff.com/") 
# Click on Sign in link 
driver.find_element_by_xpath("//a[@class='signin']").click() 
# If the checkbox is selected, then this method returns true otherwise false.
# if true no need to select the check box. 
chkboxStatus= driver.find_element_by_xpath("//a[@class='signin']").is_selected()
if(chkboxStatus):
   
print("No need to select Keep me sign in check box because already selected")
else:
    driver.find_element_by_xpath(
"//input[@id='remember'and @type='checkbox']").click()

Comments