XPath 是一种在XML 文档中定位元素的语言。因为HTML 可以看做XML 的一种实现,所以selenium 用户可是使用这种强大语言在web 应用中定位元素。
<html class="w3c">
<body>
<div class="page-wrap">
<div id="hd" name="q">
<form target="_self" action="http://www.so.com/s">
<span id="input-container">
<input id="input" type="text" x-webkit-speech="" autocomplete="off" suggestwidth="501px" >
用绝对路径定位:
find_element_by_xpath("/html/body/div[2]/form/span/input")
相对路径定位:
find_element_by_xpath("//input[@id=’input’]")
#通过自身的id 属性定位
find_element_by_xpath("//span[@id=’input-container’]/input")
#通过上一级目录的id 属性定位
find_element_by_xpath("//div[@id=’hd’]/form/span/input")
#通过上三级目录的id 属性定位
find_element_by_xpath("//div[@name=’q’]/form/span/input")
#通过上三级目录的name 属性定位
XPath 可以做布尔逻辑运算,例如://div[@id=’hd’ or @name=’q’]
缺陷也非常明显:
1、性能差,定位元素的性能要比其它大多数方式差;
2、不够健壮,XPath
会随着页面元素布局的改变而改变;
3. 兼容性不好,在不同的浏览器下对XPath 的实现是不一样的。