自动化测试学习(五) selenium命令之定位页面元素2014-08-23定位页面元素对于很多selenium命令,target域是必须的。Target在web页面范围内识别UI元素,它使用locatorType=location的格式。在很多情况下,locatorType可以省略,下面举例方式来描述各种类型的locatorType.假如,有如下一段HTML代码:
html><body><form id= "loginForm" ><input name= "username" type= "text"/><input name= "password" type= "password"/><input name= "continue" type= "submit" value= "Login"/><input name= "continue" type= "button" value= "Clear"/><a href= "continue.html" >Continue</a></form></body></html>
我们看看selenium提供了那些定位方式:1. identifier定位这是最普遍的一种定位方式,当不能识别为其它定位方式后,默认为dientifier定位,在这种策略下,第一个使用id的页面元素将被识别出来,如果没有使用指定id的元素,那么将识别第一个名字与指定条件相符的元素。identifier识别html各项元素的定位策略如下:identifier=loginForm //定位页面元素为fromidentifier=username //定位页面元素为usernameidentifier=Continue //定位页面元素为Continue因为identifier定位是默认方式,因此“identifier=” 可以不写。Continue //同样表示定位页面元素为Continue2. id定位这种定位方式比identifier定位范围更窄,当然也更具体,如果你知道元素id特征,就使用这种方式:id=loginFrom //定位页面元素from3. name定位名称定位方式将会识别第一个匹配名称属性的UI元素。如果多个元素拥有相同的名称属性,可以使用过滤器来进一步优化你的定位策略。默认的过滤器是Value (匹配value特征):name=username //定位页面元素为usernamename=Continue value=Clear //定位页面元素为Continue ,值为Clearname=Continue type=button //定位页面元素为Continue ,类型为button提示:上述三种定位器使得selenium可以不依赖于UI元素在页面上的位置而进行测试。所以,当页面结构发生变化时,测试依然可以通过。有时候,设计人员频繁改动页面的情况,通过id和name特征定位元素就变的非常重要。4. XPath定位XPath是一种在XML文档中定位元素的语言。因为HTML可以看做XML的一种实现,所以selenium用户可是使用这种强大语言在web应用中定位元素。XPath扩展了上面id和name定位方式,提供了很多种可能性,比如定位页面上的第三个多选框。xpath=/html/body/form[1] //绝对路径(html的任何轻微改变都会导致失败)//form[1] //HTML中的第三个form元素xpath=//form[@id="loginForm"] //id为loginFrom的元素//input[@name="username"] //input元素且其name为‘username’//form[@id="loginForm"]/input[1] //针对id为‘loginForm’的form,定位它的第一个input元素//input[@name="continue"][@type="button"] //name为‘continue’且type为‘button’的input//form[@id="loginForm"]/input[4] //id为‘loingForm’的form,定位它的第四个input元素。扩展阅读:W3C XPath Recommendation:http://www.w3.org/TR/xpath/XPath Tutorial: http://www.zvon.org/xxl/XPathTutorial/General/examples.htmlhttp://www.w3.org/TR/xpath/Firefox插件,可以帮助你获取页面元素的XPath:XPath Checker Firebug