selenium clear() command doesn't clear the ele

2019-06-26 04:39发布

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() method, later while executing next command (click event), the text area I had previously cleared, is now populated with previously filled value.

Here is the code snippet:

mobileNumField.get(0).clear();
Thread.sleep(4500);
emailAddress.get(0).click();
emailAddress.get(0).clear();
Thread.sleep(4500);
emailAddress.get(0).sendKeys(Keys.TAB);

4条回答
Deceive 欺骗
2楼-- · 2019-06-26 04:57

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));
查看更多
▲ chillily
3楼-- · 2019-06-26 04:58

It's possible that the fields you're trying to fill has autocomplete attribute set to on. [Reference]

If clear() works when the line executes then it's safe to say that this is not a webdriver specific issue.

It would help if you can show the html snippet of the page section you're working on.

Possible areas of debugging:

  • forcefully remove autocomplete attribute on page load using java script executor
  • turn off autocomplete setting on the driver level. I believe the solution would vary depending on the driver being used.

    Good luck!

    PS: Those Thread.sleep(s) are not advisable.

  • 查看更多
    别忘想泡老子
    4楼-- · 2019-06-26 05:09

    Another way that worked for me in python, but is not what you would call elegant:

    for _ in range(4):
        risk_percentage.send_keys(Keys.BACK_SPACE)
    
    查看更多
    The star\"
    5楼-- · 2019-06-26 05:15

    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);
    }
    
    查看更多
    登录 后发表回答