如何使用 Selenium 和 C# 将鼠标悬停在一个项目上避免点击它

How to hover over an item avoiding a click on it using Selenium and C#

我有一个问题,我想将鼠标悬停在某个按钮上(开发)但是我不想点击它,我不知道该怎么做。当我点击这个按钮时,它会将我带到另一个地方,我不想要它

 private void button1_Click(object sender, EventArgs e)
        {
            string url = textBox1.Text;
            driver.Navigate().GoToUrl(url); Thread.Sleep(2000);

            driver.FindElement(By.XPath("//button[@id='onetrust-accept-btn-handler']")).Click(); Thread.Sleep(3000);

            driver.FindElement(By.XPath("//a[normalize-space()='Mój OLX']")).Click(); Thread.Sleep(2000); 

            driver.FindElement(By.XPath("//section[@class='login-page has-animation']//input[@id='userEmail']")).SendKeys("anastazja.bendkowska@wp.pl"); Thread.Sleep(3000);

            driver.FindElement(By.XPath("//input[@id='userPass']")).SendKeys("Anastazja12345");

            driver.FindElement(By.XPath("//section[@class='login-page has-animation']//button[@id='se_userLogin']")).Click(); Thread.Sleep(3000);

            driver.FindElement(By.XPath("//div[@class='css-1povu0j']"));


            //driver.FindElement(By.XPath("//a[normalize-space()='Wyloguj']")).Click();
            //driver.FindElement(By.XPath("")).Click();


        }

您可以在找到要悬停的元素后使用Action

    var element = driver.FindElement(By.XPath("//div[@class='css-1povu0j']"));
    Actions action  = new Actions(driver);
    action.MoveToElement(element).Perform();

要将鼠标悬停在某个按钮上但要避免单击它,您必须引入 for the desired ElementIsVisible() and the use Actions Class 方法,如下所示:

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
var element = wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("//a[normalize-space()='Wyloguj']")));

Actions action  = new Actions(driver);
action.MoveToElement(element).Perform();

参考资料

您可以在以下位置找到一些相关的详细讨论: