无法选中复选框

2024-05-13 14:43:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图检查复选框,但我得到以下错误

selenium.common.exceptions.NoSuchElementException: Message: no such 
element: Unable to locate element: {"method":"xpath","selector":"//mat- 
checkbox[@id='mat-checkbox-1']/label/div"}

我尝试使用id、css选择器和xpath进行选择,但仍然出现错误。在

^{pr2}$

复选框的HTML是

<div _ngcontent-fep-c23="" class="last-date my-12 ng-star-inserted" fxlayout="column" style="flex-direction: column; box-sizing: border-box; display: flex;">
<mat-checkbox _ngcontent-fep-c23="" class="mat-checkbox mat-accent ng-untouched ng-pristine ng-valid" formcontrolname="deadline_enabled" id="mat-checkbox-1">
    <label class="mat-checkbox-layout" for="mat-checkbox-1-input">
        <div class="mat-checkbox-inner-container">
            <input class="mat-checkbox-input cdk-visually-hidden" type="checkbox" id="mat-checkbox-1-input" tabindex="0" aria-checked="false">
            <div class="mat-checkbox-ripple mat-ripple" matripple="">
                <div class="mat-ripple-element mat-checkbox-persistent-ripple"></div>
            </div>
            <div class="mat-checkbox-frame"></div>
            <div class="mat-checkbox-background">
                <svg xml:space="preserve" class="mat-checkbox-checkmark" focusable="false" version="1.1" viewBox="0 0 24 24">
                    <path class="mat-checkbox-checkmark-path" d="M4.1,12.7 9,17.6 20.3,6.3" fill="none" stroke="white"></path>
                </svg>
                <div class="mat-checkbox-mixedmark"></div>
            </div>
        </div><span class="mat-checkbox-label"><span style="display:none">&nbsp;</span>The event has a registration deadline</span>
    </label>
</mat-checkbox>
<!---->


Tags: pathdividinput错误elementngxpath
3条回答

您可能正在尝试单击不是“checkbox”类型的元素。我看到有一个输入带有类型复选框。请尝试下面提到的代码

reg_date_checkbox = self.browser.find_element_by_xpath("//input[@id='mat-checkbox-1-input']")
reg_date_checkbox.click()

另外,如果希望执行uncheck,可以在执行单击之前查找输入元素的aria checked属性是否为true。在

你可以试试这个:

element = self.browser.find_element_by_css("input#mat-checkbox-1-input")
element.click()

您使用的是这个xpath //matcheckbox[@id='mat-checkbox-1']/label/div,它应该是//mat-checkbox[@id='mat-checkbox-1']/label/div,中间有一个-,您缺少这个。在

您仍然可以尝试使用这个css选择器:

div.mat-checkbox-inner-container input[class^='mat-checkbox-input'][id^='mat-checkbox']

可能复选框在iframe中,如果是这样,那么首先切换到frame,然后尝试单击复选框。在

相关问题 更多 >