Monday, April 17, 2017

Different methods to scroll down a window in selenium test (code is in C#)

Sometime we used to scroll down a window as per our automation requirement and we have following methods to do it:

Method 1: Using Action Call and keydown event
Method 2: Using Java Script
Method 3: using Action class and movetoelement function

Check the below code to use all three methods:

using System;
using OpenQA.Selenium.Chrome;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SikuliSharp;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium;


namespace UnitTestProject1
{
    [TestClass]
   
    public class ScrollDown
    {

        [TestMethod]
        public void TestMethod2()
        {
            ChromeDriver driver = new ChromeDriver(@"E:\Drivers");
            driver.Navigate().GoToUrl("http://robotframework.org/");


            // Method 1 to scroll down a window with action class and Key.Down even

            Actions action = new Actions(driver);

            for (int a = 1; a < 10; a = a + 1)
            {
                action.SendKeys(Keys.Down).Perform();
            }


            // Method 2 to scroll down a window with Java Script executor

            ((IJavaScriptExecutor)driver).ExecuteScript("window.scrollTo(0,1050)");


            //Method 3 to scroll down a window with Action class. Find an element and move to that element

            IWebElement element = driver.FindElement(By.Id("chat"));
            Actions actions = new Actions(driver);
            actions.MoveToElement(element);
            actions.Perform();

        }
    }

}

No comments:

Post a Comment