Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait in selenium webdriver until the text of 5 characters length is entered

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.

like image 568
Abhinay Avatar asked Oct 27 '25 05:10

Abhinay


2 Answers

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)
                }
            });
like image 195
Johnny Avatar answered Oct 29 '25 03:10

Johnny


You can do this by using the following:

  • FluentWait
  • private Wait<WebDriver> wait = new FluentWait<>(yourWebDriverInstance).withTimeout(10, TimeUnit.SECONDS).pollingEvery(500, TimeUnit.MILLISECONDS).ignoring(NoSuchElementException.class);
    

  • A custom expected conditions method:
  • private Function<WebDriver, Boolean> expectedConditions(boolean condition) {
            return driver -> condition;
        }
    

  • Method calling the custom expected conditions:
  • 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).

    like image 35
    iamkenos Avatar answered Oct 29 '25 03:10

    iamkenos