Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click on a checkbox element using python and selenium

I am trying to automate loading and configuring a web page. On this page I am trying to check the state of the checkbox and then click on a it if its unchecked.

HTML code for the page:

<fieldset id="wireless-24" class="left" style="display: block;">
                <div class="legend-edit text-orphan">
                    <legend>2.4 GHz network</legend><span>|</span><span id="edit-wireless-24"><a id="editWireless24Link" href="http://192.168.0.1/ui/1.0.99.162351/dynamic/home.html#">Edit</a></span>
                </div>
                <div class="row toggle-edit">
                    <label style="width: 126px;">Network:</label>
                    <label id="w-radio-enabled-text-24">Disabled</label> <!-- code sets the text to either Enabled or Disabled -->
                    <div class="cell" id="w-enabled-span-24">
                        <div class="check-item" style="">
                            <div><input type="checkbox" id="w-enabled-24" name="radio.band24.settings.isEnabled" class="ui-helper-hidden-accessible"><span class="ui-checkbox"></span></div>
                            <div><label for="w-enabled-24" class="ui-checkbox">Enabled</label></div>
                        </div>
                    </div>
                </div>

Network is the field I am trying to click on. I am using selenium and python.

I tried the following:

browser.find_element_by_id("w-radio-enabled-text-24").send_keys("Enabled")
browser.find_element_by_text("Network").click() 
like image 664
Klot Avatar asked Aug 23 '26 18:08

Klot


1 Answers

Firstly, you are trying to send_keys to label tag, what is wrong. You can send_keys to input tag or equivalent. Secondly, you are trying to click on the label, what from my perspective also not effective. I believe you want something like this:

checkbox = driver.find_element_by_id('w-enabled-24') # locate checkbox
if not checkbox.is_selected(): # check if checkbox is already selected
    checkbox.click() # if not, click on it

Also I would add WebDriverWait, to make sure, that element is visible and ready to be clicked like this:

checkbox = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "w-enabled-24")))

this will wait at least 10 seconds until checkbox will be clickable. The full code would be like this:

checkbox = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "w-enabled-24")))
if not checkbox.is_selected():
    checkbox.click()

Note: you have to add some imports:

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

More information about WebDriverWait you will find here.

like image 185
Andrei Suvorkov Avatar answered Aug 25 '26 07:08

Andrei Suvorkov