如何在Firefox 19中使用Selenium WebDriver进行鼠标悬停?

2022-09-02 23:47:14

我用了硒2.31。

我使用操作类进行鼠标移动。使用此功能,我将鼠标移到菜单上,其子菜单仅显示几分之一秒,这与旧版本的Firefox不同。

由于此问题,我无法选择子菜单,因为它会引发异常“元素无法滚动到视图中”。driver.findElement

有什么解决方案吗?


答案 1

使用操作对象时,应首先移动菜单标题,然后移动到弹出菜单项并单击它。别忘了在最后打电话。下面是一些示例 Java 代码:actions.perform()

Actions actions = new Actions(driver);
WebElement menuHoverLink = driver.findElement(By.linkText("Menu heading"));
actions.moveToElement(menuHoverLink);

WebElement subLink = driver.findElement(By.cssSelector("#headerMenu .subLink"));
actions.moveToElement(subLink);
actions.click();
actions.perform();

答案 2

另一种方法是使用Selenium的JavaScript Executor来强制显示元素的样式。

这方面的一个例子是沿着C中的这条线#

//Use the Browser to change the display of the element to be shown
 (IJavaScriptExecutor)driver).ExecuteScript("document.getElementById('myId').stlye.display="block");

//navigate to your link that is now viewable 
driver.FindElement(By.Xpath('//LinkPath')).Click(); 

从那里,您可以找到元素的XPath,并使用硒单击该元素。您可以层叠它以找到主要元素的子元素

//(IJavaScriptExecutor)ffbrowser).ExecuteScript("document.getElementById('myId').children[1].children[1].style.display='block'");

请注意,仅当您有一个悬停元素在悬停时更改显示样式时,才有可能做到这一点。


推荐