Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Di chuyển con trỏ chuột đến vị trí hoặc element cụ thể bằng C# và Selenium

Trong Selenium WebDriver C#, di chuyển chuột dùng class Actions. Tạo object Actions, dùng method MoveToElement truyền locator element, cuối cùng gọi Perform() để thực thi.

Sau khi di chuyển đến element, có thể click bằng Click(). Để di chuyển đến tọa độ cụ thể, dùng MoveByOffset(x, y) truyền offset theo trục x, y.

Cú pháp


Actions actions = new Actions(driver);
actions.MoveByOffset(10, 20).Perform();
actions.Click().Perform();

// Move đến element
IWebElement element = driver.FindElement(By.Name("txtname"));
actions.MoveToElement(element).Perform();

Ví dụ: Di chuyển đến link "Library" và click


using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Interactions;
using System;

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 actions = new Actions(driver);
            actions.MoveToElement(l);
            actions.Click();
            actions.Perform();

            Console.WriteLine("Page title: " + driver.Title);
        }

        [TearDown]
        public void CloseBrowser()
        {
            driver.Quit();
        }
    }
}

Kết quả

Trang điều hướng đến Library, title in ra console.