Moving mouse pointer to a specific location or element using C# and Selenium

SeleniumCsharpAutomation TestingTesting Tools

We can move mouse pointer to a specific location or element in Selenium webdriver(C#) using the Actions class. We have to first create an object of this class.

Next to move an element we have to apply the MoveToElement method and pass the element locator as a parameter to this method. Finally, to actually perform this task the method Perform is to be used.

After moving to an element, we can click on it with the Click method. To move to a specific location, we have to use the MoveByOffset method and then pass the offset numbers to be shifted along the x and y axis as parameters to it.

Syntax

Actions a = new Actions(driver);
a.MoveByOffset(10,20).Perform();
a.Click().Perform()
//move to an element
IWebElement l = driver.FindElement(By.name("txtnam"));
a.MoveToElement(l).Perform();

Let us try to move the mouse to the Library link and then click it.

Example

using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
namespace NUnitTestProject2{
   public class Tests{
      String url = "https://www.tutorialspoint.com/index.htm";
      IWebDriver driver;
      [SetUp]
      public void Setup(){
         //creating object of FirefoxDriver
         driver = new FirefoxDriver("");
      }
      [Test]
      public void Test2(){
         //URL launch
         driver.Navigate().GoToUrl(url);
         //identify element
         IWebElement l = driver.FindElement(By.XPath("//*[text()='Library']"));
         //object of Actions class
         Actions a = new Actions(driver);
         //move to element
         a.MoveToElement(l);
         //click
         a.Click();
         a.Perform();
         Console.WriteLine("Page title: " + driver.Title);
      }
      [TearDown]
      public void close_Browser(){
         driver.Quit();
      }
   }
}

Output

raja
Published on 07-Apr-2021 08:38:14
Advertisements