Tuesday 18 March 2014

Working with Checkboxes in Selenium Webdriver in Python - Example

We can first see if the checkbox is selected using is_selected() method. Then using click method we can perform the operations such as selecting or deselecting the checkboxes as illustrated in the below example.


from selenium import webdriver

from selenium.webdriver.support.ui import Select


driver = webdriver.Firefox()

driver.maximize_window()

driver.get("http://register.rediff.com/register/register.php")

try:
   
elem= driver.find_element_by_name("chk_altemail")
  
   if (elem.is_selected()):

       print("Checkbox is selected..now deselecting")

      elem.click()

   else:

       print("Checkbox is not selected..now selecting it")

      elem.click()
   
   driver.close()

except Exception as e:

    print ("Exception occured", format(e));

finally:

    driver.quit()

    print ("finally")



What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

4 comments:

  1. What if you had 9 checkboxes on a page. The first 2 are supposed to be checked and the last 7 are supposed to be unchecked. You want to assert that's the case when you get to that page. Is there a way you could write a loop of some kind to check the status of those checkboxes using python webdriver? Thanks!

    ReplyDelete
    Replies
    1. Yes - You can definitely write a loop to see the status of specific check boxes.

      Delete
  2. Do you need the "Select" import?

    ReplyDelete

Buy Best Selenium Books

Contributors