使用C#和Selenium將滑鼠指標移動到特定位置或元素


我們可以使用Actions類在Selenium webdriver (C#)中將滑鼠指標移動到特定位置或元素。我們首先需要建立此類的物件。

接下來,要移動元素,我們需要應用MoveToElement方法並將元素定位器作為引數傳遞給此方法。最後,要實際執行此任務,需要使用Perform方法。

移動到元素後,我們可以使用Click方法單擊它。要移動到特定位置,我們必須使用MoveByOffset方法,然後將沿x軸和y軸移動的偏移量作為引數傳遞給它。

語法

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();

讓我們嘗試將滑鼠移動到“圖書館”連結,然後單擊它。

示例

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://tutorialspoint.tw/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();
      }
   }
}

輸出

更新於:2021年4月7日

6000+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.