1,为什么要用xpath
从watir支持对象属性操作上看,唯一较多document对象支持的识别属性,一个是ID,一个是xpath属性。
从现在网站代码来看,很多对象是没有ID的,如果此时让开发为了自动化,加这样的ID
可谓是工程浩瀚。。。,由下表,可得出结论:
http://wiki.openqa.org/display/WTR/Methods+Supported+by+Element
xpath表达式,是watir强有力的标识web对象的方法。其内部原理是把页面HTML转换成为
XHTML,然后REXML来解析它,以致于可以用xpath表达式语言在文档结构中作查询定位。
另外,用xpath可以让watir开发脚本,更简炼。
最后,xpath可以操作html中扩展tag,或watir不支持的tag操作
基于以上三种原因,我们需要研究xpath技术。。。
2,工具
Tutorial:
http://www.w3schools.com/xpath/default.asp
view xpath:
安装firefox:http://www.mozillaonline.com/
https://addons.mozilla.org/zh-CN/firefox/addon/1192?id=1192或
安装xpath checker:https://addons.mozilla.org/zh-CN/firefox/addon/1095?id=1095
3,包安装
已上传到SVN中
1.2. Xpath格式与语法
总结一下,xpath查询需要搞清楚,以下三种语法
1, Select Nodes (选择结点)
2, Predicates(断言)
3,模糊与条件表达
具体格式请参照:http://www.w3schools.com/xpath/xpath_syntax.asp
注意:Unfortunately, there are different ways of dealing with XML and XPath in Internet Explorer based browsers and other browsers (like Mozilla based browsers).
1.3. 应用场景
1, watir不支持的tag,可以用element_by_xpath方法
如:
<html>
<body>
<map name="chart">
<area shape="poly" coords="150,16,159,17,168,20,175,25,182,32,150,56,150,56" >
<area shape="poly" coords="182,32,188,43,190,56,150,56,150,56" href="PieChart.html?category=Critical&pieIndex=0">
</map>
</body>
</html>
脚本实现如下:
# get the underlying object and execute click method
ie.element_by_xpath("//area[contains(@href , 'PieChart.html')]/").click
2,使用xpath在标准HTML对象属性识别上
<table> <tr>
<td><img src="1.jpg">First Image</td>
</tr>
</table>
<table>
<tr>
<td><img src="2.jpg">Second Image</td>
</tr>
</table>
<table>
<tr>
<td><img src="3.jpg">Third Image</td>
</tr>
</table>
若不用xpath,实现只点击3.jpg的方法:
ie.tables.each do |t| # since you don't have ID's, look at every table
for i in 1..t.row_count # for every row in this table
t[i].each do |cell| # for every column in this row, look at its contents
if cell.image(:src, /3.jpg/).exists? # if true, this is your cell
puts cell.text
end
end
end
end
但是用xpath就是非常简练:
ie.cell(:xpath, "//img[@src='3.jpg']/").click()
3, tag中含有tag不识别的属性,但IE没有报错
<select foo="bar"> <option value="1">1< /option> < /select>
如上对象是一个下拉框,但若foo="bar"是select tag不支持的,
基于现有watir版本,不提供识别此对象的方法,但xpath也可以访问到
如:element = browser.select(:xpath, "//select[@foo='bar']")
从watir API来看,很多对象都支持xpath方法,后面我也会不断补充应用场景
1.4. Xpath其它内置方法
<<请参照watir技术集锦>>