Java WebDriver 查找不包含属性的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18770486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:54:06  来源:igfitidea点击:

WebDriver find Element not containing attribute

javaextjsseleniumwebdriverselenium-webdriver

提问by aeinstein83

I have following HTML

我有以下 HTML

<button class="x-btn-text " style="position: relative; width: 69px;" type="button" tabindex="0" aria-disabled="false">OK</button>
<button class="x-btn-text" style="position: relative; width: 69px;" type="button" tabindex="0">OK</button>

The first button is disabled and the second button is enabled, since I want to click on the enabled button. Is there a way I could find the element, that doesn't have attribute aria-disabled?

第一个按钮被禁用,第二个按钮被启用,因为我想点击启用的按钮。有没有办法找到没有属性的元素aria-disabled

采纳答案by Yi Zeng

ExtJs case. Here you need determine if it's enabled or not by attribute aria-disabled="false"using getAttribute("aria-disabled")or XPath/CssSelector.

ExtJs 案例。在这里,您需要通过属性aria-disabled="false"usinggetAttribute("aria-disabled")或 XPath/CssSelector确定它是否已启用。

So Code Enthusiastic's logic should be correct, however ExtJS is always special on something.

所以Code Enthusiastic 的逻辑应该是正确的,但是ExtJS 在某些方面总是很特别。

List<WebElement> okButtons = driver.findElements(By.xpath("//button[text() = 'OK']"));
for (WebElement okButton : okButtons) { 
    if (!okButton.getAttribute("aria-disabled").equals("false")) {
        okButton.click();
        break;
    }
}

Or even easier, rule out the enabled one in your locator. (As you need to text here, so no suitable locator using CssSelector, only XPath)

或者更简单的是,排除定位器中启用的那个。(由于您需要在此处输入文本,因此没有合适的定位器使用 CssSelector,只有 XPath)

WebElement enabledokButton = driver.findElement(By.xpath("//button[text() = 'OK' and not(@aria-disabled = 'false')]"));
enabledokButton.click();

回答by Code Enthusiastic

List<WebElement> okButtons = driver.findElements(By.xpath("//button[text() = 'OK']"));
for (WebElement okButton : okButtons) { 
    if (okButton.isEnabled()) {
        okButton.click();
        break;
    }
} 

回答by ddavison

Is there a way I could find the element, that doesn't have attribute aria-disabled?

有没有办法找到没有 aria-disabled 属性的元素?

YES! Utilize CSS!

是的!使用CSS!

Your selector to find a button without the aria-disabledattribute would be, button:not([aria-disabled])

您查找没有该aria-disabled属性的按钮的选择器将是,button:not([aria-disabled])

driver.findElement(By.cssSelector("button:not([aria-disabled])").click();