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-selector 和 xpath 进行选择,但不断出错。
reg_date_checkbox = self.browser.find_element_by_xpath("//matcheckbox[@id='mat-checkbox-1']/label/div")
reg_date_checkbox.location_once_scrolled_into_view
reg_date_checkbox.click()
复选框的 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"> </span>The event has a registration deadline</span>
</label>
</mat-checkbox>
<!---->
解决方案
您可能正在尝试单击不是“复选框”类型的元素。我看到有一个带有类型复选框的输入。请尝试下面提到的代码
reg_date_checkbox = self.browser.find_element_by_xpath("//input[@id='mat-checkbox-1-input']")
reg_date_checkbox.click()
此外,如果您希望执行取消选中,您可以在执行单击之前查找输入元素的 aria-checked 属性是否为真。
推荐阅读
- gradle - 如何修复 IntelliJ IDEA 中冲突的 Kotlin 依赖项?
- asp.net-core-2.0 - 使用 ASP.NET Core 的 AutoMapper 扩展在启动时编译映射
- javascript - 什么 __typename 应该处于 Apollo Link 状态?
- android - ConstraintLayout 和加权链的问题
- c++ - unique_ptr 的 static_cast 到 void *,带有构造函数参数
- java - 如何从 Intellij Idea 中的项目文件夹导入图像
- javascript - 更新后无法从 smsgateway.me 发送短信
- php - php 配置:未找到 PHP 可执行文件
- html - 用html组织图片
- java - Hibernate 给出了无法确定类型错误