針對頁面上的二級菜單,需要鼠標懸停才能進行操作。

/** * Clicks (without releasing) in the middle of the given element. This is equivalent to: * <i>Actions.moveToElement(onElement).clickAndHold()</i> * * @param onElement Element to move to and click. * @return A self reference. */ public Actions clickAndHold(WebElement onElement) { action.addAction(new ClickAndHoldAction(mouse, (Locatable) onElement)); return this; }
使用方法:最后一定不要忘記perform()
Actions actions = new Actions(driver); actions.clickAndHold(webElement).perform();
或者:
Actions actions = new Actions(driver); actions.moveToElement(webElement).clickAndHold().perform();
或者:使用js來模擬鼠標懸停
/** * JScript實現鼠標懸停
* @author lozz */ public void mouseHoverJScript(WebElement HoverElement) { // TODO Auto-generated method stub try { if (isElementPresent(HoverElement)) { String mouseOverScript = "if(document.createEvent){var evObj = document.createEvent('MouseEvents');evObj.initEvent('mouseover', true, false); arguments[0].dispatchEvent(evObj);} else if(document.createEventObject) { arguments[0].fireEvent('onmouseover');}"; ((JavascriptExecutor) driver).executeScript(mouseOverScript, HoverElement); } else { System.out.println("Element was not visible to hover " + "\n"); } } catch (StaleElementReferenceException e) { // TODO: handle exception System.out.println("Element with " + HoverElement + "元素未附加到頁面文檔" + e.getStackTrace()); } catch (NoSuchElementException e) { // TODO: handle exception System.out.println("Element " + HoverElement + " 元素未在DOM中沒有找到" + e.getStackTrace()); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); System.out.println("懸停時發生錯誤" + e.getStackTrace()); } }
--- 轉載請說明來源 ,thx