How to get the total number of checkboxes in a page using Selenium?

We can get the total number of checkboxes in a page using Selenium webdriver using find_elements method. While working on any checkboxes, we will always find an attribute type in the html code and its value should be checkbox.

This characteristic is only applicable to checkboxes on that particular page and no other types of UI elements like edit box, link and so on.

To retrieve all the elements with attribute type = 'checkbox', we will use find_elements_by_xpath() method. This method returns a list of web elements with the type of xpath specified in the method argument. In case there are no matching elements, an empty list will be returned.

After the list of checkboxes is fetched, to count its total numbers, we need to get the size of that list. The size of the list can be obtained from the len() method of the list data structure.

Finally, this length is printed on the console.




Code Implementation for counting checkbox.

from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
#get method to launch the URL
#to refresh the browser
# identifying the checkboxes with type attribute in a list
chk =driver.find_elements_by_xpath("//input[@type='checkbox']")
# len method is used to get the size of that list
#to close the browser