Checking Radio Buttons
Radio buttons are an example of web elements which can be used to make some kind of selections in a web page. The crux of handling a radio button is a method called is_selected( )
, which checks if an option is selected or not. We can use to verify if a radio button or even a check box is selected or not , and then we can use the result to process further events.
Here we’re trying to see if the Wednesday radio button is selected. If so, then we’re going to click on the Monday radio button and then take a screenshot.
__author__ = 'rahul' import unittest from selenium import webdriver class MyChkbox(unittest.TestCase): def setUp(self): self.driver =webdriver.Firefox() def test_Chkbox(self): driver = self.driver driver.maximize_window() driver.get('http://openwritings.net/sites/default/files/radio_checkbox.html') elewed = driver.find_element_by_xpath("//*[@id='daysofweek']/input[3]") elemon = driver.find_element_by_xpath("//*[@id='daysofweek']/input[1]") if elewed.is_selected(): print("Wednesday is selected") elemon.click() self.assertTrue(elemon.is_selected(), "Monday is selected") driver.save_screenshot('/home/rahul/Downloads/chkbox1' '.png') else: print("Test failed") def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main()
Checking CheckBoxes
Similarly, as with Radio buttons, we can use the is_selected( )
method for check boxes as well.
__author__ = 'rahul' import unittest from selenium import webdriver class MyRadiobtn(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() def test_Radiobtn(self): driver = self.driver driver.maximize_window() driver.get('http://openwritings.net/sites/default/files/radio_checkbox.html') eleapple= driver.find_element_by_name('apple') elebanana= driver.find_element_by_name('orange') if eleapple.is_selected(): eleapple.click() elebanana.click() driver.save_screenshot('/home/rahul/Downloads/radiobtn1' '.png') def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main()
Head over to Git to access this code.