ย้าย Mouse Pointer ไปยังตำแหน่งหรือ Element ใน Selenium WebDriver (C#) ด้วย Class Actions สร้าง Object Actions แล้วใช้เมธอดต่างๆ
ย้ายไป Element: ใช้ MoveToElement ส่ง Element Locator แล้ว Perform() หลังย้ายไป Element สามารถ Click() ได้ ย้ายไปตำแหน่งเฉพาะ: ใช้ MoveByOffset ส่ง Offset X, Y
Syntax
Actions a = new Actions(driver);
a.MoveByOffset(10, 20).Perform();
a.Click().Perform();
// Move to Element
IWebElement l = driver.FindElement(By.Name("txtnam"));
a.MoveToElement(l).Perform();ตัวอย่าง: ย้ายเมาส์ไป Link "Library" แล้ว Click
ตัวอย่างโค้ด
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System;
using OpenQA.Selenium.Interactions;
namespace NUnitTestProject2
{
public class Tests
{
String url = "https://www.tutorialspoint.com/index.htm";
IWebDriver driver;
[SetUp]
public void Setup() => driver = new FirefoxDriver();
[Test]
public void Test2()
{
driver.Navigate().GoToUrl(url);
IWebElement l = driver.FindElement(By.XPath("//*[text()='Library']"));
Actions a = new Actions(driver);
a.MoveToElement(l).Click().Perform();
Console.WriteLine("Page title: " + driver.Title);
}
[TearDown]
public void CloseBrowser() => driver.Quit();
}
}ผลลัพธ์
Page title: Library - Tutorials Point