How to get webDriver to wait for page to load (C# Selenium project)

后端 未结 7 1277
北荒
北荒 2020-12-04 22:57

I\'ve started a Selenium project in C#. Trying to wait for page to finish loading up and only afterwards proceed to next action.

My code looks like this:

<         


        
7条回答
  •  天命终不由人
    2020-12-04 23:25

    I did this to address this type of issue. It's a combination of timers and loops that are looking for a specific element until it timesout after a certain number of milliseconds.

    private IWebElement FindElementById(string id, int timeout = 1000)
    {
        IWebElement element = null;
    
        var s = new Stopwatch();
        s.Start();
    
        while (s.Elapsed < TimeSpan.FromMilliseconds(timeout))
        {
            try
            {
                element = _driver.FindElementById(id);
                break;
            }
            catch (NoSuchElementException)
            {
            }
        }
    
        s.Stop();
        return element;
    }
    

    I also made one for element enabled

    private IWebElement ElementEnabled(IWebElement element, int timeout = 1000)
    {
        var s = new Stopwatch();
        s.Start();
    
        while (s.Elapsed < TimeSpan.FromMilliseconds(timeout))
        {
            if (element.Enabled)
            {
                return element;
            }
        }
    
        s.Stop();
        return null;
    }
    

提交回复
热议问题