如何使用 Java 在 Selenium WebDriver 中检查元素是否可点击
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42293387/
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
How to check if element is clickable in Selenium WebDriver using Java
提问by user3190414
I have to check that a text box accepts only a particular number of characters. If the characters exceed, it doesn't give any error but only turn the text in red. Another text box simply doesn't accept additional characters. How do I verify that text box doesn't accept more characters in both cases?
我必须检查一个文本框是否只接受特定数量的字符。如果字符超过,它不会给出任何错误,而只会将文本变为红色。另一个文本框根本不接受其他字符。我如何验证文本框在两种情况下都不接受更多字符?
One option I have is, check if the 'Save' button which is visible on the page is clickable. How do I do this with Selenium WebDriver in Java?
我的一种选择是,检查页面上可见的“保存”按钮是否可点击。如何使用 Java 中的 Selenium WebDriver 执行此操作?
回答by sForSujit
Just write the below method and call it whenever you want to check whether the element is clickable or not. Pass the required arguments also.
只需编写以下方法并在您想检查元素是否可点击时调用它。还传递所需的参数。
public static boolean isClickable(WebElement el, WebDriver driver)
{
try{
WebDriverWait wait = new WebDriverWait(driver, 6);
wait.until(ExpectedConditions.elementToBeClickable(el));
return true;
}
catch (Exception e){
return false;
}
}
回答by Santosh Hegde
You can use isEnabled()
to check if an element is enabled or not.
您可以isEnabled()
用来检查元素是否已启用。
driver.findElement(By.xpath("//path/to/element").isEnabled();
This will return true
if the button is clickable.
true
如果按钮可点击,这将返回。
回答by SantiBailors
If by clickable you mean not disabled, you can use WebElement.isEnabled()
.
如果通过可点击表示未禁用,则可以使用WebElement.isEnabled()
.
About the text input that doesn't accept additional characters, if you want to detect that instead, it depends on how that constraint is enforced. For example if it's done through a maxlength attributeyou can try to read that attribute from your input
element (WebElement.getAttribute(String)
). In this case you would know in advance how many characters you can send to the textbox.
关于不接受附加字符的文本输入,如果您想检测它,则取决于该约束的实施方式。例如,如果它是通过maxlength 属性完成的,您可以尝试从您的input
元素 ( WebElement.getAttribute(String)
) 中读取该属性。在这种情况下,您会提前知道可以发送到文本框的字符数。
About the text input that turns the text to red, if you want to detect that you should first find out how the text is turned to red; probably it does that by setting a CSS class
or style
attribute to your input
element, in which case you can try to read that attribute from the element.
关于把文字变成红色的文字输入,如果要检测应该先搞清楚文字是怎么变成红色的;可能是通过为元素设置 CSSclass
或style
属性来实现的input
,在这种情况下,您可以尝试从元素中读取该属性。