'sendKeys' are not working in Selenium WebDriver

后端 未结 12 1599
暗喜
暗喜 2020-12-05 13:36

I am not able to put any value in my application using WebDriver. My application is using frames.

I am able to clear the value of my textbox with driver.findEle

12条回答
  •  隐瞒了意图╮
    2020-12-05 14:21

    I had a similar problem recently and tried some of the suggestions above, but nothing worked. In the end it fell back on a brute-force retry which retries if the input box wasn't set to what was expected.

    I wanted to avoid thread.sleep for obvious reasons and saw different examples of it failing that looked like some kind of race or timing condition.

    public void TypeText(string id, string text)
    {
        const int numberOfRetries = 5;
        for (var i = 1; i < numberOfRetries; i++)
        {
            try
            {
                if (TryTypeText())
                    return;
            }
            catch (Exception)
            {
                if (i == numberOfRetries)
                    throw;
            }
        }
    
        bool TryTypeText()
        {
            var element = _webDriver.FindElement(By.Id(id));
            element.Click();
            element.Clear();
            element.SendKeys(text);
            if (element.TagName.ToLower() == "input"
                && !DoesElementContainValue(element, text, TimeSpan.FromMilliseconds(1000)))
            {
                throw new ApplicationException($"Unable to set the type the text '{text}' into element with id {id}. Value is now '{element.GetAttribute("value")}'");
            }
            return true;
        }
    }
    
    private bool DoesElementContainValue(IWebElement webElement, string expected, TimeSpan timeout)
    {
        var wait = new WebDriverWait(_webDriver, timeout);
        return wait.Until(driver =>
        {
            try
            {
                var attribute = webElement.GetAttribute("value");
                return attribute != null && attribute.Contains(expected);
            }
            catch (StaleElementReferenceException)
            {
                return false;
            }
        });
    }
    

提交回复
热议问题