WebDriverWait is not waiting for the element I specify

蓝咒 提交于 2020-07-10 06:21:29

问题


I am trying to get my code to wait for an element to appear before trying to get the text from the element. If I step through the code allowing the element time to appear it works as expected, but if I run it without breakpoints the wait appears to be ignored and an exception is raised.

I don't understand why it is being ignored?

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
IWebElement message = wait.Until(driver => driver.FindElement(By.ClassName("block-ui-message")));
string messageText = message.Text;

回答1:


As an alternative you can induce WebDriverWait for the ElementIsVisible() and you can use the following Locator Strategy:

string messageText = new WebDriverWait(driver, TimeSpan.FromSeconds(30)).Until(ExpectedConditions.ElementIsVisible(By.ClassName("block-ui-message"))).GetAttribute("innerHTML");

Using DotNetSeleniumExtras.WaitHelpers with nuget:

Not that super clear what exactly you meant by specific using directive I need. In-case you are using SeleniumExtras and WaitHelpers you can use the following solution:

string messageText = new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.ClassName("block-ui-message"))).GetAttribute("innerHTML");



回答2:


Below sample code will wait until the element is presented

        private bool IsElementPresent(By by)
        {
            try
            {
                _driver.FindElement(by);
                return true;
            }
            catch (NoSuchElementException)
            {
                return false;
            }
        }

        private void WaitForReady(By by)
        {
            var wait = new WebDriverWait(_driver, TimeSpan.FromHours(2));
            wait.Until(driver =>
            {
                //bool isAjaxFinished = (bool)((IJavaScriptExecutor)driver).ExecuteScript("return jQuery.active == 0");
                return IsElementPresent(by);
            });
        }

      // ...
      // Usage
      WaitForReady(By.ClassName("block-ui-message")); // It will wait until element which class name is 'block-ui-message' is presented to page


来源:https://stackoverflow.com/questions/57554298/webdriverwait-is-not-waiting-for-the-element-i-specify

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!