selenium clear() command doesn't clear the element

前端 未结 8 1229
旧时难觅i
旧时难觅i 2021-01-11 21:14

I have been writing selenium scripts for a while in Java. I encountered a very weird issue today.

Here is the issue: I cleared a text field using webelement.clear()

相关标签:
8条回答
  • 2021-01-11 21:45

    I solved it by adding a function to my BasePage to clear fields by a given WebElement.

     public void clearWebField(WebElement element){
        while(!element.getAttribute("value").equals("")){
            element.sendKeys(Keys.BACK_SPACE);
        }
    }
    

    You can also implement this method in the page that experiencing the problem.

    0 讨论(0)
  • 2021-01-11 21:54

    I had a similar issue with a text field that used an auto-complete plugin. I had to explicitly clear the attribute value as well as do a SendKeys. I created an extension method to encapsulate the behaviour, hopefully the snippet below will help:

    public static void SendKeysAutocomplete(this IWebElement element, string fieldValue)
    {
       element.SendKeys(fieldValue);
       element.SetAttribute("value", fieldValue);
    }
    
    public static void SetAttribute(this IWebElement element, string attributeName, string attributeValue)
    {
       var driver = WebDriverHelper.GetDriverFromScenarioContext();
    
       var executor = (IJavaScriptExecutor)driver;
       executor.ExecuteScript("arguments[0].setAttribute(arguments[1], arguments[2]);", element, attributeName, attributeValue);
    }
    
    0 讨论(0)
  • 2021-01-11 21:55

    Faced a similar problem. The input field is cleared but the error message is not updated. It seems that some input fields work correctly only if you enter and delete a character:

    element.sendKeys(text);
    element.sendKeys(Keys.SPACE, Keys.BACK_SPACE);
    
    0 讨论(0)
  • 2021-01-11 21:55

    I am using Mac and the following code helps also

      public static void macCleanHack(WebElement element) {
            String inputText = element.getAttribute("value");
            if( inputText != null ) {
                for(int i=0; i<inputText.length();i++) {
                    element.sendKeys(Keys.BACK_SPACE);
                }
            }
    
        }
    
    0 讨论(0)
  • 2021-01-11 21:56

    I don't know the exact reason for your element keeping its value, but you can try an alternative text clearance by sending 'Ctrl+A+Delete' key combination using sendKeys method of the element's object:

    emailAddress.sendKeys(Keys.chord(Keys.CONTROL,"a", Keys.DELETE));
    
    0 讨论(0)
  • 2021-01-11 21:56

    Hope this helps to clear the field and then sendKeys() the needed value

     while (!inputField.getAttribute("value").equals("")) {
            inputField.sendKeys(Keys.BACK_SPACE);
           }
            inputField.sendKeys("your_value");
    
    0 讨论(0)
提交回复
热议问题