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

Time:07-15

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()
driver.maximize_window()
driver.get(
    "https://www.sugarcrm.com/request-demo/")

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")
    else:
        driver.find_element_by_xpath("//input[@type='checkbox']").click()

CodePudding user response:

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")
    else:
        element.click()
  • Related