How to check check boxes using selenium framework with Python

41 Views Asked by At
column_of_hobbies = row['Hobbies']

for hobby in column_of_hobbies:
    hobbies_xpath = f"//*[contains(@class, 'custom-checkbox') and .//*[contains(.,'{hobby}')]]"
    hobbies_checkbox = wait.until(EC.presence_of_element_located((By.XPATH, hobbies_xpath)))
    driver.execute_script("arguments[0].scrollIntoView(true);", hobbies_checkbox)
    time.sleep(1)
    hobbies_checkbox.click()

With this above code , I am not able to click properly on the check box of this form https://demoqa.com/automation-practice-form.

Its not throwing error but checking the check boxes multiple times.Ho can I make it click only once?

Any possible solution would help.

1

There are 1 best solutions below

1
Sandeep Nakka On

hobbies_path="//input[@class='custom-control-input' and @type='checkbox']" By using above path you will get the all the check boxes of the hobbies

    checkboxes = driver.find_elements(By.XPATH, "//input[@class='custom-control-input' and @type='checkbox']")
if checkboxes:
    checkboxes[0].click()
    print("Clicked the first checkbox.")
else:
    print("No checkboxes found on the page.")

you can select the required option by checkboxes[0].click() or checkboxes[1].click() or checkboxes[2].click()