selenium -- 鼠标悬停

Posted 面向zz编程

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了selenium -- 鼠标悬停相关的知识,希望对你有一定的参考价值。

针对页面上的二级菜单,需要鼠标悬停才能进行操作。

技术分享
/**
   * 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;
  }
View Code

使用方法:最后一定不要忘记perform()

Actions actions = new Actions(driver);
actions.clickAndHold(webElement).perform();

或者:

Actions actions = new Actions(driver);
actions.moveToElement(webElement).clickAndHold().perform();

或者:使用js来模拟鼠标悬停

/**
     * JScript实现鼠标悬停
     */
    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

以上是关于selenium -- 鼠标悬停的主要内容,如果未能解决你的问题,请参考以下文章

使用 Python 和 Selenium 将鼠标悬停在图形上

python selenium 鼠标悬停

python selenium 模拟鼠标悬停,为啥看不到效果

selenium -- 鼠标悬停

有没有办法使用 Selenium 和 Python 绑定执行鼠标悬停(悬停在元素上)?

Selenium3+python3--如何定位鼠标悬停才显示的元素