I am trying to automate an application which involves CAPTCHA. I tried to use WebDriverWait with below code:
WebDriverWait mywait = new WebDriverWait(driver,20);
mywait.until(ExpectedConditions.attributeToBeNotEmpty(driver.findElementByClassName("loginCaptcha"),"value"));
Now the problem here is as soon as I enter the first character of captcha in the text, the above condition becomes true and the next statements are getting executed which results in invalid captcha error.
Is there any way to wait until 5 characters are entered in the text box(my captcha is always 5 characters fixed in length.)
PS: I dont want to use static waits.
First of all, you should not try and solve CAPTCHA with selenium. The whole purpose of CAPTCHA is to prevent UI automation. If you want to overcome CAPTCHA, you should use internal APIs of your SUT.
Regarding waiting for specific text length, it should be something like:
//First init WebDriverWait to 20 sec
WebDriverWait mywait = new WebDriverWait(driver, 20);
//Locator to your DOM element
By byClass = By.class("loginCaptcha");
//Wait until text box has value greater or equal 5 character
mywait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return (d.findElement(byClass).getAttribute ("value").length() >= 5)
}
});
You can do this by using the following:
private Wait<WebDriver> wait = new FluentWait<>(yourWebDriverInstance).withTimeout(10, TimeUnit.SECONDS).pollingEvery(500, TimeUnit.MILLISECONDS).ignoring(NoSuchElementException.class);
private Function<WebDriver, Boolean> expectedConditions(boolean condition) {
return driver -> condition;
}
public void waitUntilElemValueLengthEquals(WebElement element, int length) {
try {
wait.until(expectedConditions(element.getAttribute("value").length == length));
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
throw e;
}
}
USAGE:
WebElement e = driver.findElementByClassName("loginCaptcha");
waitUntilElemValueLengthEquals(e,5);
SIDE NOTE:
For an actual implementation, it would be good if you can create a class which implements the WebDriver interface. That class will contain all the WebDriver interface methods AND all your custom methods (like the ones above).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With