首页 > 解决方案 > isEnabled() 方法总是返回 true

问题描述

我想获取启用复选框的字符串列表。但是当我使用 isEnabled() 时,即使是禁用的复选框,它也总是返回 true。在输出中,我得到了该字段中所有字符串的列表。

以下是我为它编写的代码:-

@FindBy(css = "[class *= 'CheckboxTextAligned']")
    private List<WebElement> airportListCheckbox;

public void getEnabledValues() {
        for (WebElement elements : airportListCheckbox) {
            if(elements.isEnabled()==true) {
                for (WebElement airportText : airportListTextName) {
                    airportText.getText();
                    LOG.info(airportText.getText());                
                }
            }       
        }

HTML 代码如下:- 对于禁用复选框:-

<label role="checkbox" aria-label="checkbox" class="inputs__CheckboxTextAligned undefined undefined">
<input type="checkbox" disabled checked>
<span class="inputs__box"><svg width="16px" height="16px" class="inputs__checkIcon" viewBox="0 0 1024 1024">
<path d="434z"></path></svg></span>
<span class="inputs__text">London City</span></label>

对于启用复选框: -

<label role="checkbox" aria-label="checkbox" class="inputs__CheckboxTextAligned undefined undefined">
<input type="checkbox" checked="">
<span class="inputs__box"><svg width="16px" height="16px" class="inputs__checkIcon" viewBox="0 0 1024 1024">
<path d="133z"></path></svg></span>
<span class="inputs__text">London Gatwick</span></label>

标签: javaseleniumselenium-webdriver

解决方案


当您尝试验证输入节点是启用还是禁用时,isEnabled() 检查元素上的 disabled 属性。如果属性“禁用”不存在,则返回 True。

试试下面的代码:

@FindBy(xpath = "//label[contains(@class, 'CheckboxTextAligned')]/following::input")
private List<WebElement> airportListCheckbox;

public void getEnabledValues() {
for (WebElement elements : airportListCheckbox) {
    if(elements.isEnabled()) {
        for (WebElement airportText : airportListTextName) {
        airportText.getText();
        LOG.info(airportText.getText());                
        }
    }       
}

当您想检查输入节点是否启用时,您需要稍微更改定位器,因为之前您尝试检查标签是否启用/禁用而不是输入节点所以您总是正确的。


推荐阅读