zoukankan      html  css  js  c++  java
  • Seleniumwebdriver系列教程(12)————fire event的替代方案

    webdriver里面已经没有了fire_event方法,就像世界上再也没有萨达姆,本拉登和卡扎菲一样。

    不过我们可以通过其他方法来实现fire_event的相似功能。

    考虑下面的html,当鼠标悬停到Mouse Over Here链接上时,js的mouseover事件被触发,shwo_tips()函数将被执行,隐藏的tips div会显示在页面上。

    <html>
        <head>
            <title>FireEvent</title>
            <style>
                .mo {color: blue;}
                .tips {display:none;border: 1px solid #ccc; background-color:#EFEFEF; 100px;height:100px}
            </style>
            <script>
                function show_tips(){
                    document.getElementById("t").style.display = "block";
                }
                function hide_tips(){
                    document.getElementById("t").style.display = "none";
                }
            </script>
        </head>
        <body>
            <a class = "mo" href = "#" onmouseover = "show_tips()" onmouseout = "hide_tips()">Mouse Over Here</a>
            <div id = "t" class = "tips">This is the tips of link</div>
        </body> 
    </html>
    

    如果存在fire_event方法的话,直接在Mouse Over Here链接上触发oumouseover就能达到显示隐藏div的效果了,但是webdriver取消了fire_event,所以这时候我们就需要求助于另一个功能强大的类,Action类。

    Action类给用户提供了一些模拟用户交互方法,比如模拟key_down,key_up, double_click等。

    下面的代码使用Action类的move_to方法模拟了鼠标的悬停事件,需要注意3点:

    • Action类并不需要显示的实例化,调用时只需要通过driver.action直接调用该实例既可;

    • move_to方法执行完毕后悬停的效果也就消失了,所以代码中使用了循环10次的方法来人为"延长"事件的持续时间;

    • 调用move_to方法只是注册但并未真正的触发实际动作,需要调用perform方法来执行注册了的动作;

      require 'rubygems'
      require 'selenium-webdriver'
      dr = Selenium::WebDriver.for :firefox
      select_file = 'file:///'.concat File.expand_path(File.join(File.dirname(__FILE__), 'fire_event.html'))
      dr.navigate.to select_file
      
      m = dr.find_element(:css => '.mo')
      10.times do 
      	dr.action.move_to(m).perform
      end
      

      另外也可以直接调用js引擎执行show_tips函数,这样就不需要去模拟事件了。

      js = %q[show_tips();]
      dr.execute_script js
      

      点击下面的链接下载本文源码

      fire_event

    b

  • 相关阅读:
    一本通1281:最长上升子序列 暨 LIS DP求解
    STL初步
    【洛谷P3369】【模板】普通平衡树
    【洛谷P4859】已经没有什么好害怕的了
    【CF961G】Partitions
    【洛谷P4718】【模板】Pollard-Rho算法
    【LOJ#143】质数判定
    【CF917D】Stranger Trees
    【洛谷P3700】小Q的表格
    【洛谷P4245】【模板】任意模数多项式乘法
  • 原文地址:https://www.cnblogs.com/nbkhic/p/2221905.html
Copyright © 2011-2022 走看看