Selenium-webdriver系列教程(12)————fire event的替代方案

webdriver里面已经没有了fire_event方法,就像世界上再也没有萨达姆,本拉登和卡扎菲一样。不过我们可以通过其他方法来实现fire_event的相似功能。考虑下面的html,当鼠标悬停到Mouse Over Here链接上时,js的mouseover事件被触发,show_tips()函数将被执行,隐藏的tips div会显示在页面上。

<html>    <head>        <title>FireEvent</title>        <style>            .mo {color: blue;}            .tips {display:none;border: 1px solid #ccc; background-color:#EFEFEF;width: 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 :firefoxselect_file = 'file:///'.concat File.expand_path(File.join(File.dirname(__FILE__), 'fire_event.html'))dr.navigate.to select_filem = dr.find_element(:css => '.mo')10.times dodr.action.move_to(m).performend

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

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

只想到处流浪人生就像一场旅行,不必在乎目的地,

Selenium-webdriver系列教程(12)————fire event的替代方案

相关文章:

你感兴趣的文章:

标签云: