【问题标题】:How to mouseover on a webelement using Selenium WebDriver with Java如何使用 Selenium WebDriver 和 Java 将鼠标悬停在 web 元素上
【发布时间】:2013-01-19 11:58:24
【问题描述】:

如何使用 Selenium Webdriver 执行鼠标悬停功能?

测试用例就像说,打开雅虎网站,登录旁边有链接(邮件)。 鼠标悬停时,它会显示一个工具提示。

当我尝试下面的代码时,它不是鼠标悬停在确切的位置,而是悬停在其他地方。我哪里出错了?

还请告诉我,如何捕获工具提示?

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;


public class Sample 
{
    public static void main(String[] args) 
    {
        WebDriver driver=new FirefoxDriver();
        driver.get("http://www.yahoo.com");

        driver.manage().window().maximize();

        try 
                {
            Thread.sleep(5000);
        } catch (InterruptedException e)
                {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        WebElement lMail=driver.findElement(By.xpath("//*[@title='Mail']"));

        Actions builder=new Actions(driver);
        builder.moveToElement(lMail).build().perform();


    }

}

【问题讨论】:

  • 代码看起来很正常,你看到它悬停在哪里?
  • 我同意 Ardesco,代码看起来正确。我看到你和我使用的唯一区别是我不会在perform() 之前调用build()。所以我最后的电话是这样的:new Actions(driver).moveToElement(element).perform();

标签: java selenium-webdriver


【解决方案1】:
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();

【讨论】:

    【解决方案2】:

    试试这个代码:

    //Assume driver initialized properly.
    WebElement element = driver.findElement(By.id("Element id"));
    Locatable hoverItem = (Locatable) element;
    Mouse mouse = ((HasInputDevices) driver).getMouse();
    mouse.mouseMove(hoverItem.getCoordinates());
    

    【讨论】:

    • 我在这里看到了一些奇怪的行为。当我在 Win XP 机器上运行相同的代码时,鼠标悬停在对象上,但在 Win 7 中,鼠标悬停在不同的位置。在上述两个代码中,它只是将鼠标悬停在链接上并且在光标移开之后(指向一些不同的随机位置)。这是为什么?有人可以帮忙吗?
    • 在 XP 机器上运行时,您可以直观地看到 tooltip 文本(在您的情况下为 Mail)?
    【解决方案3】:

    我使用了类似的代码,它对我有用。 我还在几个地方使用了以下内容: browser.executeScript("jQuery('mycss-selector').mouseover();") 您将不得不使用 css-selector,而不是 xpath。

    【讨论】:

      猜你喜欢
      • 2013-04-24
      • 2021-07-15
      • 2011-11-08
      • 2018-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多