Powered By Blogger

Search Here!

Showing posts with label WebDriver. Show all posts
Showing posts with label WebDriver. Show all posts

Tuesday, August 4, 2015

Change The Download Path For IE using C# !

We can change the download path in IE which helps to verify the download file using Webdriver in IE.

RegistryKey rKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Internet Explorer\Main", true);
            if (rKey != null)

              rKey.SetValue("Default Download Directory", @"E:\E$", RegistryValueKind.String);

For disabling Download Prompt, we can use ESC key by Selenium or change IE settings using RegEdit.

Sunday, October 12, 2014

Example: How To Handle Page Synchronization and Loading In Angular JS Site using Webdriver !

This method helps you to wait till Progress bar still on page.

public void HoldTillPageSynchronizationCompletes()
        {
            bool isPageInProgress = HoldTillElementIsVisible(By.CssSelector("div[class=Progress]"), 5);
            if (isPageInProgress)
            {
                var stopWatch = new Stopwatch();
                stopWatch.Start();
                while (stopWatch.Elapsed.TotalMinutes < _waitTimeOut)
                {
                    string isPageStillInProgress = WebDriver.FindElement(By.CssSelector("table[id=mydivimg]")).GetAttribute("style");
                    if (isPageStillInProgress.Contains("display: none;"))
                    {
                        stopWatch.Stop(); break;
                    }
                }
            }
        }


This method helps you to wait till search records visible on page.

public void HoldTillRecordLoadInPageCompletes()
        {
            bool isLoadRecordInProgress = HoldTillElementIsVisible(By.CssSelector("div[style='display: block;']"), 5);
            if (isLoadRecordInProgress)
            {
                var stopWatch = new Stopwatch();
                stopWatch.Start();
                while (stopWatch.Elapsed.TotalMinutes < _waitTimeOut)
                {
                    string isLoadRecordStillInProgress = WebDriver.FindElement(By.CssSelector("div[id=load_Summary]")).GetAttribute("style");
                    if (isLoadRecordStillInProgress.Contains("display: none;"))
                    {
                        stopWatch.Stop(); break;
                    }
                }
            }
        }

This is a common method helps you to hold for finding the element. In this element surely visible on the page but after sometime.

protected bool HoldTillElementIsVisible(By by, int timeOut = -1)
        {
            //Wait For Element
            if (timeOut == -1)
            {
                timeOut = this._waitTimeOut;
            }
            try
            {
                WebDriverWait wait = new WebDriverWait(WebDriver, TimeSpan.FromSeconds(timeOut));
                wait.Until(ExpectedConditions.ElementIsVisible(@by));
                return true;
            }
            //Exception Handling
            catch (Exception)
            {
                return false;
            }
        }

Sunday, June 16, 2013

Create Logging In Webdriver !

private static IWebDriver IEWebDriver()
        {
            //Get The Machine Processor Architecture
            String getProcessorArchitecture = Microsoft.Win32.Registry.GetValue(
                "HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\Environment"
                , "PROCESSOR_ARCHITECTURE", null).ToString();
            //Get IE Driver Path
            String getIeDriverPath =
                (Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase)
                + "\\..\\..\\..\\..\\ExternalAssemblies\\" + ((getProcessorArchitecture == "x86") ? "x86" : "x64")).Replace("file:\\", "");
            //Start Internet Explorer Driver Service
            InternetExplorerDriverService ieservice = InternetExplorerDriverService.CreateDefaultService(getIeDriverPath);
            ieservice.LoggingLevel = InternetExplorerDriverLogLevel.Trace;
            //Get Log Execution Path
            String getExecutingPath = new FileInfo(Assembly.GetExecutingAssembly().Location).DirectoryName;
            ieservice.LogFile = Path.Combine(getExecutingPath, "Log", "IEDriver" + DateTime.Now.Ticks + ".log");
            //Set Internet Explorer Options
            InternetExplorerOptions options = new InternetExplorerOptions
                                                  {
                                                      IntroduceInstabilityByIgnoringProtectedModeSettings = true,
                                                      UnexpectedAlertBehavior = InternetExplorerUnexpectedAlertBehavior.Ignore,
                                                      IgnoreZoomLevel = true,
                                                      EnableNativeEvents = true,
                                                      RequireWindowFocus = true,
                                                  };
            //Create Internet Explorer Driver Object
            IWebDriver webDriver = new InternetExplorerDriver(ieservice, options, TimeSpan.FromMinutes(20));
            //Set WebDriver Page Load Time
            webDriver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(timeOut));
            //Set The Cursor Position Center of the Screen
            Cursor.Position = new Point(Screen.PrimaryScreen.Bounds.Width / 2, Screen.PrimaryScreen.Bounds.Height / 2);
            return webDriver;
        }

Saturday, June 8, 2013

Internet Explorer Options : Selenium !

org.openqa.selenium.ie.InternetExplorerDriver

Capabilities [{platform=WINDOWS, elementScrollBehavior=0, javascriptEnabled=true, enablePersistentHover=true, ignoreZoomSetting=false, browserName=internet explorer, enableElementCacheCleanup=true, unexpectedAlertBehaviour=dismiss, version=9, cssSelectorsEnabled=true, ignoreProtectedModeSettings=false, allowAsynchronousJavaScript=true, requireWindowFocus=false, handlesAlerts=true, initialBrowserUrl=, nativeEvents=true, takesScreenshot=true}]

InternetExplorerOptions options = new InternetExplorerOptions
                                                  {
                                                      IntroduceInstabilityByIgnoringProtectedModeSettings = true,
                                                      UnexpectedAlertBehavior = InternetExplorerUnexpectedAlertBehavior.Ignore,
                                                      IgnoreZoomLevel = true,
                                                      EnableNativeEvents = true,
                                                      RequireWindowFocus = true,
                                                      EnablePersistentHover = true,
                                                      ElementScrollBehavior = InternetExplorerElementScrollBehavior.Top,
                                                      BrowserAttachTimeout = TimeSpan.FromSeconds(timeOut),
                                                  };
 IWebDriver webDriver = new InternetExplorerDriver(ieDriverPath, options, TimeSpan.FromMinutes(20));

Properties Description

Name
Description
ElementScrollBehavior
Gets or sets the value for describing how elements are scrolled into view in the IE driver. Defaults to scrolling the element to the top of the viewport.
EnableNativeEvents
Gets or sets a value indicating whether to use native events in interacting with elements.
EnablePersistentHover
Gets or sets a value indicating whether to enable persistently sending WM_MOUSEMOVE messages to the IE window during a mouse hover.
IgnoreZoomLevel
Gets or sets a value indicating whether to ignore the zoom level of Internet Explorer .
InitialBrowserUrl
Gets or sets the initial URL displayed when IE is launched. If not set, the browser launches with the internal startup page for the WebDriver server.
IntroduceInstabilityByIgnoringProtectedModeSettings
Gets or sets a value indicating whether to ignore the settings of the Internet Explorer Protected Mode.
RequireWindowFocus
Gets or sets a value indicating whether to require the browser window to have focus before interacting with elements.
UnexpectedAlertBehavior
Gets or sets the value for describing how unexpected alerts are to be handled in the IE driver. Defaults to Default.

Monday, April 29, 2013

Selenium : Scroll Automatically Before Click On Element

If you want to click() on a WebElement, but it is not showing because it is in invisible state. So, we need scroll the WebElement to make it in visible state and perform click() action.


((JavascriptExecutor) webDriver).executeScript "arguments[0].scrollIntoView(true);", webelementObject); 

Monday, February 25, 2013

Handle 'HTML text editor' in selenium RC and WebDriver

We could not directly insert text in the HTML editor. To automate the HTML editor we need to first click on the Show view source image button in the Editor tool box and then we can able to insert text in HTML editor text area.


WebDriver.FindElement(By.Id("viewsource")).Click();

WebDriver.FindElement(By.Id("txtHTMLEditor_textarea")).SendKeys("This is my Text!");



Friday, February 22, 2013

How to run same script on FF/IE/Chrome in Webdriver

Setting the Browser key in the app.config, we can execute the same script in the different browser(s).
        
         ///
        /// Returns an instance of the web driver based on test browser.
        ///

        /// The browser driver.

        public static IWebDriver GetInstance()
        {
            string browserName = ConfigurationManager.AppSettings["Browser"];
            IWebDriver webDriver = null;
            switch (browserName)
            {
                case Internet_Explorer: webDriver = IEWebDriver(); break;
                case FireFox: webDriver = FireFoxWebDriver(); break;
                case Safari: webDriver = SafariWebDriver(); break;
                case Chrome: webDriver = ChromeWebDriver(); break;
                default: throw new ArgumentException("The suggested browser was not found");
            }
            return webDriver;
        }

         ///
        /// Returns an instance of IE based driver.
        ///

        /// IE based driver.

        private static IWebDriver IEWebDriver()
        {
            IWebDriver webDriver = new InternetExplorerDriver(ieDriverPath, options, TimeSpan.FromMinutes(20));            webDriver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(timeOut));
            //Set The Cursor Position Center of the Screen
            Cursor.Position = new Point(Screen.PrimaryScreen.Bounds.Width / 2, Screen.PrimaryScreen.Bounds.Height / 2);
            return webDriver;
        }

        ///
        /// Returns an instance of Firefox based driver.
        ///

        /// FireFox based driver.

        private static IWebDriver FireFoxWebDriver()
        {
            IWebDriver webDriver = new FirefoxDriver();            webDriver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(timeOut));
            //Set The Cursor Position Center of the Screen
            Cursor.Position = new Point(Screen.PrimaryScreen.Bounds.Width / 2, Screen.PrimaryScreen.Bounds.Height / 2);
            return webDriver;
        }

        ///
        /// Returns an instance of Safari based driver.
        ///

        /// Safari based driver

        private static IWebDriver SafariWebDriver()
        {
            IWebDriver webDriver = new SafariDriver();            webDriver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(timeOut));
            return webDriver;
        }

        ///
        /// Returns an instance of Chrome based driver.
        ///

        /// Chrome based driver.

        private static IWebDriver ChromeWebDriver()
        {
            IWebDriver webDriver = new ChromeDriver(
                (Path.GetDirectoryName(
                System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
                + "\\..\\..\\..\\..\\ExternalAssemblies").Replace("file:\\", ""));
            return webDriver;
        }
    }

Add browser key in the app.config -
<add key="Browser" value="Internet Explorer" />

WebDriver: Refresh IFrame on the Page

Refresh the IFrame not the whole page. Pass the IFrame name in the method.

        ///
        /// Refresh the current selected iframe.
        ///

        /// This is the name of the Iframe.
        /// Executes JavaScript in the context of the currently selected frame or window.
        /// The script fragment provided will be executed as the body of an anonymous function.

        /// Indicates that a driver can execute JavaScript, providing
        /// access to the mechanism to do so.

        protected void RefreshIFrameByJavaScriptExecutor(string iFrameName)
        {            ((IJavaScriptExecutor)WebDriver).ExecuteScript(string.Format("document.getElementById('{0}').src = " + "document.getElementById('{0}').src", iFrameName));
        } 

Saturday, February 16, 2013

Webdriver wait for window get loads and then select window

Wait for window get loads and then select the window.

///
/// Wait for window till it gets load on the page.
///

/// The name of the window.
/// This is time to wait.
/// if the window not loads in the specified interval of time.

/// If the window not exists on the page.

        protected void WaitUntilWindowLoads(string windowName, int timeOut = -1)
        {
            // Intialization of bool 'isWindowPresent' for checking window present
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
            if (timeOut == -1)
            {
                timeOut = this.waitTimeOut;
            }
            while (stopWatch.Elapsed.TotalSeconds < timeOut)
            {
                try
                {
                    //Wait for window
                    if (WaitUntilWindow(windowName) == true) break;
                }
                catch (Exception)
                {
                    // For Any exceptions catch value is assinged false
                }
            }
        }
  
///

/// Is Window Opened In the Specified Interval of Time or not.
///

/// This is the name of the window.
/// This is the time to wait for window get open.
/// True if the window is opened otherwise false.

/// If the window not able to find in the specified time.

/// If the window not exists on the page.

        protected bool WaitUntilWindow(string windowName, int timeOut = -1)
        {
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
            if (timeOut == -1)
            {
                timeOut = this.waitTimeOut;
            }
            while (stopWatch.Elapsed.TotalSeconds < timeOut)
            {
                if (WebDriver.WindowHandles.Any(item => WebDriver.SwitchTo().Window(item).Title == windowName))
                {
                    return true;
                }
            }
            stopWatch.Stop();
            return false;
        }

Webdriver Handling IEdriver.exe path of 32/64 bit machine !

Webdriver handling IEdriver.exe for 32 Bit and 64 bit machine. Now, we don’t need to bother to change every time the path for IEdriver.exe for 32/64 bit machine. Just add the below code and keep both IEdriver.exe file in a folder and it would automatically choose according to machine configuration.

String processorArchitecture = Microsoft.Win32.Registry.GetValue(
                "HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\Environment"
                , "PROCESSOR_ARCHITECTURE", null).ToString();

            string ieDriverPath =
                (Path.GetDirectoryName(
                System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
                + "\\..\\..\\..\\..\\ExternalAssemblies\\" + ((processorArchitecture == "x86") ? "x86" : "x64")).Replace("file:\\", "");

Webdriver Ignoring UnexpectedAlertBehavior and Zoom Level

With 'UnexpectedAlertBehavior' option we can do any work in front like chatting while in background window scripts are executing and 'IgnoreZoomLevel ' we can also run scripts at any zoom level.

InternetExplorerOptions options = new InternetExplorerOptions

                                                  {
                                                      IntroduceInstabilityByIgnoringProtectedModeSettings = true,
                                                      UnexpectedAlertBehavior = InternetExplorerUnexpectedAlertBehavior.Ignore,
                                                      IgnoreZoomLevel = true                                                     
                                                  };
IWebDriver webDriver = new InternetExplorerDriver(ieDriverPath, options, TimeSpan.FromMinutes(10));            webDriver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(timeOut));
return webDriver;