Selenium 2 and Synchronization

Once you have your logging sorted out, the next thing you need to be concerned with is synchronization. In Selenium 1, this was accomplished with the dozen or so wait_for variants. In Selenium 2, they are gone and replaced with some new synchronization methods.

I’m sure there is an official way of doing synchronization in Selenium 2, but I have yet to figure it out. Needing something now though, here is a class that you can use to start getting synchronization in your C# scripts. A big thanks to David Burns for the original direction on the WaitForElement one.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
 
using NUnit.Framework;
 
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Internal;
 
namespace Element34
{
    static class Waits
    {
        public static IWebElement WaitForElement(IWebDriver driver, By by)
        {
            IWebElement element;
            for (int second = 0; ; second++)
            {
                if (second >= 60) Assert.Fail("timeout");
                try
                {
                    element = driver.FindElement(by);
                    if (element != null) break;
                }
                catch (Exception)
                { }
                Thread.Sleep(1000);
            }
            return element;
        }
 
        public static IWebElement WaitForElementVisible(IWebDriver driver, By by)
        {
            IWebElement element;
            for (int second = 0; ; second++)
            {
                if (second >= 60) Assert.Fail("timeout");
                try
                {
                    element = driver.FindElement(by);
                    if (element != null)
                    {
                        IRenderedWebElement tmpElement = (IRenderedWebElement)driver.FindElement(by);    
                        if (tmpElement.Displayed)
                        {
                            break;
                        }
                    }
                }
                catch (Exception)
                { }
                Thread.Sleep(1000);
            }
 
            return element;
        }
 
        public static void WaitForFrame(IWebDriver driver, String frame)
        {
            for (int second = 0; ; second++)
            {
                if (second >= 60) Assert.Fail("timeout");
                try
                {
                    driver.SwitchTo().Frame(frame);
                    break;
                }
                catch (Exception)
                { }
                Thread.Sleep(1000);
            }
        }
    }
}

Post a Comment

Your email is never published nor shared. Required fields are marked *