How to check all checkboxes on a webpage with Selenium in Python (using a loop)


I am attempting to write a python program that will check all checkboxes on a given webpage. Currently, I only have the ability to select a single checkbox and am unsure why I am not able to iterate through the loop of elements containing checkboxes on this example page. Here is my code so far:

from selenium import webdriver
driver = webdriver.Firefox()

elements = []
elements = driver.find_elements_by_xpath("//*[@class='form-check-input']")
elemlength = len(elements)

for x in range(1, elemlength):
    if driver.find_element_by_xpath("//input[@type='checkbox']").is_selected():
        print("Already Selected")


driver.find_element_by_xpath("//input[@type='checkbox']") will return the first checkbox it finds every time, so it will always be the same one.

You can use the list of elements returned by driver.find_elements_by_xpath("//*[@class='form-check-input']") instead.

elements = driver.find_elements_by_xpath("//*[@class='form-check-input']")
for element in elements:
    if element.is_selected():
        print("Already Selected")

Answered By – Henry

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published