Home > Software design >  Python Selenium check all checkboxes on page
Python Selenium check all checkboxes on page

Time:12-13

I'm trying to tick all checkboxes on a page. There are about 50 of them and this code seems to work but only ticks what is visible on the screen. It doesn't scroll down the table and tick the remaining boxes.

def select_checkbox():
    checkboxes = driver.find_elements_by_css_selector("//input[@type='checkbox']")
    for checkbox in checkboxes:
        if not checkbox.is_selected():
            checkbox.click() # to tick it

I'm thinking It's only finding those on the screen as the rest are still loading. I need to wait until all checkboxes have loaded but I'm not sure about how to go about this. Any help is appreciated.

Below is the table row

<input type="checkbox" value="1" name="admin_contract_form[price_forms_attributes][51][offered]" id="admin_contract_form_price_forms_attributes_51_offered">

CodePudding user response:

You can use explicit waits presence_of_all_elements_located for all the checkboxes.

Also, to scroll driver.execute_script("arguments[0].scrollIntoView(true);", checkbox) this will likely to get the job done.

Code:

wait = WebDriverWait(driver, 30)
def select_checkbox():
    checkboxes = wait.until(EC.presence_of_all_elements_located((By.XPATH, "//input[@type='checkbox']")))
    for checkbox in checkboxes:
        driver.execute_script("arguments[0].scrollIntoView(true);", checkbox)
        if not checkbox.is_selected():
            checkbox.click() # to tick it

Imports:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

CodePudding user response:

Select all the desired inducing WebDriverWait for the visibility_of_all_elements_located() and click() the individual checkboxes inducing WebDriverWait for the element_to_be_clickable() as follows:

def select_checkbox():
    checkboxes = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "a.search-result-item[href]")))
    for checkbox in checkboxes:
        if not checkbox.is_selected():
            WebDriverWait(driver, 20).until(EC.element_to_be_clickable(checkbox)).click()

PS: click() inducing WebDriverWait will scroll the element into the view by default.

Note: You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
  • Related