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

后端 未结 7 1296
北荒
北荒 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:27

    Because of its simplicity I like this solution. Also it has the benefit of avoiding excessive waits and taking the guess work out of what might be the upper wait limit:

        public bool WaitToLoad(By by)
        {
            int i = 0;
            while (i < 600)
            {
                i++;
                Thread.Sleep(100); // sleep 100 ms
                try
                {
                    driver.FindElement(by);
                    break;
                }
                catch { }
            }
            if (i == 600) return false; // page load failed in 1 min
            else return true;
        }
    

    Which can be modified to also include a "timer" if monitoring page load latency is needed:

        public int WaitToLoad(By by)
        {
            int i = 0;
            while (i < 600)
            {
                i++;
                Thread.Sleep(100); // sleep 100 ms
                try
                {
                    driver.FindElement(by);
                    break;
                }
                catch { }
            }
            return i; // page load latency in 1/10 secs
        }
    

提交回复
热议问题