我使用过Selenium 2.31。
我使用Actions类进行鼠标移动。使用它,我将鼠标移到菜单上,但其子菜单仅在Firefox旧版本中出现了一小段时间。
由于这个问题,我不能使用driver.findElement
选择子菜单,因为它会抛出一个异常“元素无法滚动到视图中”。
这个问题有解决方案吗?
我使用过Selenium 2.31。
我使用Actions类进行鼠标移动。使用它,我将鼠标移到菜单上,但其子菜单仅在Firefox旧版本中出现了一小段时间。
由于这个问题,我不能使用driver.findElement
选择子菜单,因为它会抛出一个异常“元素无法滚动到视图中”。
这个问题有解决方案吗?
使用 actions
对象,首先移动菜单标题,然后移动到弹出式菜单项并单击它。不要忘记在最后调用 actions.perform()
。以下是一些 Java 代码示例:
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();
尝试这段代码... 这是C#代码...
//Webelement is the main menu Link
webElement = driver.FindElement(By.XPath("Your element xpath"));
Actions act = new Actions(driver);
act.MoveToElement(webElement).Perform();//This opens menu list
System.Threading.Thread.Sleep(5000);//This line will help you to hold menu
//This web element is the sub menu which is under main menu
webElement = driver.FindElement(By.XPath("Sub menu path"));
act.MoveToElement(webElement).Perform();//This opens menu list
System.Threading.Thread.Sleep(5000);//Holds menu
//This web element is the option you have to click
webElement = driver.FindElement(By.XPath("Path"));
webElement.Click();
另一种方法是使用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并使用selenium单击该元素。 您还可以级联查找主元素的子元素。
//(IJavaScriptExecutor)ffbrowser).ExecuteScript("document.getElementById('myId').children[1].children[1].style.display='block'");
如果您正在使用Ruby,这将非常有用。
1.首先需要通过xpath或id查找元素。
2.然后使用action.move_to().perform方法。
以下是代码:
hover = WAIT.until{$driver.find_element(:xpath,"xpath")}
driver.action.move_to(hover).perform
List<WebElement> list = driver.findElements(By.xpath("//a"));
for (int i=0;i<list.size();i++){
if(list.get(i).getText().equalsIgnoreCase("cacique intimates M"))
{
new Actions(driver).moveToElement(list.get(i)).click().build().perform();
System.out.println("Clicked on Parent Category");
new Actions(driver).moveToElement(list.get(i)).moveToElement(driver.findElement(By.linkText("SPECIALTY BRAS"))).click().build().perform();
break;
}
}
这个答案帮助我解决了我的问题。
我的挑战是找到菜单选项下面的链接。 在我悬停在菜单上之前,这个链接是看不见的。
对我来说至关重要的部分是发现除了悬停在菜单上之外,我还必须悬停在链接上才能与它交互。