Selenium Webdriver Python如何勾选所有复选框中的刻度线

时间:2015-10-05 16:22:23

标签: python python-2.7 selenium selenium-webdriver

我在网页上有一个复选框列表。其中一些是勾选的。我试图取消勾选的那些。如果选中它们,我的代码似乎不会取消勾选复选框。 如果我注释掉IF语句,它将勾选所有复选框。 问题出在我的IF声明中。它不会检查是否勾选了复选框。

我的代码段是:

    # uncheck all of the checkboxes if they are ticked
    def remove_ticks_from_all_checkboxes(self):
        checkboxes = self.driver.find_elements(By.XPATH, '//div[@id="match_configuration_add_match_tab_data_objects_fp_flags"]//input')
        for checkbox in checkboxes:
            if checkbox.is_selected == "True": # If checkbox is ticked
                checkbox.click() # to untick it

HTML是:

<div id="match_configuration_add_match_tab_data_objects_fp_flags">
    <div class="gwt-Label matchruleheader">Gender and title flags</div>
        <span class="gwt-CheckBox" style="display: block;">
            <input id="gwt-uid-239" type="checkbox" value="on" tabindex="0"/>
            <label for="gwt-uid-239">Gender must be present in both names</label>
        </span>
        <span class="gwt-CheckBox" style="display: block;">
            <input id="gwt-uid-240" type="checkbox" value="on" tabindex="0"/>
            <label for="gwt-uid-240">Gender must be consistent in both names</label>
        </span>
        <span class="gwt-CheckBox" style="display: block;">
            <input id="gwt-uid-241" type="checkbox" value="on" tabindex="0"/>
            <label for="gwt-uid-241">Allow gender mismatch</label>
        </span>
        <span class="gwt-CheckBox" style="display: block;">
        --- some more checkboxes
        <span class="gwt-CheckBox" style="display: block;">
        --- some more checkboxes
        <span class="gwt-CheckBox" style="display: block;">
        <span class="gwt-CheckBox" style="display: block;">
        <div class="gwt-Label matchruleheader">Name flags</div>
        <span class="gwt-CheckBox" style="display: block;">
        <span class="gwt-CheckBox" style="display: block;">
        <span class="gwt-CheckBox" style="display: block;">
        <span class="gwt-CheckBox" style="display: block;">
        <span class="gwt-CheckBox" style="display: block;">
        <div class="gwt-Label matchruleheader">Other flags</div>
        <span class="gwt-CheckBox" style="display: block;">
</div>              

如何检查我的for循环中是否勾选了复选框? 如果勾选了复选框,那么我想点击它以便取消它。

我的XPATH是正确的,因为如果我删除IF语句。 for循环将遍历所有复选框并勾选它。

谢谢,

里亚兹

1 个答案:

答案 0 :(得分:3)

is_selected 是一个方法,它返回一个布尔值,调用它:

for checkbox in checkboxes:
    if checkbox.is_selected(): # If checkbox is ticked
        checkbox.click() # to untick it