xpath的作用就是兩個字“定位”形葬,運用各種方法進行快速準確的定位外盯,推薦兩個非常有用的的firefox工具:firebug和xpath checker
定位
1.依靠自己屬性檀何,文本定位
//td[text()='xxx']
//div[contains(@class,'xxx')]
//div[@class='xxx' and @type='xxx']
2.依靠父節(jié)點定位
//div[@class='xxx']/div
//div[@id='xxx']/div
3.依靠子節(jié)點定位
//div[div[@id='xxx']]
//div[div[@name='xxx']]
4.混合型
//div[div[@name='xxx']]/img
//td[a/font[contains(text(),'xxx')]]//input[@type='xxx']
xpath的學習-拓展
1.following-sibling
following-sibling即為“選擇當前節(jié)點之后的所有同級節(jié)點”扔亥,那么沒有加上“sibling”關鍵字的挂签,搜索的就是之上/之下的所有節(jié)點,忽略同級概念凯力,例如:
? ?
要定位第二個input://input[@id='123']/following-sibling::input
2.preceding-sibling
preceding-sibling的解釋是“選取當前節(jié)點之前的所有同級節(jié)點”,那么沒有加上“sibling”關鍵字的礼华,搜索的就是之上/之下的所有節(jié)點咐鹤,忽略同級概念,? ???? ? ??? ? ? ? ? ? ?? ??preceding-sibling和following-sibling是剛好相反的
text
? ?
要定位第二個input://input[@id='123']/preceding-sibling::span
3.contains
和字面意思一樣就是包含圣絮,例如://div[contains(@class,'xxx')]
4.starts-with
和字面意思一樣就是以某某開頭祈惶,例如://input[starts-with(@class,'xxx')]
5.not
就是否定的意思
比如找一個id不為123的input:input[not[id='123']]
又如找一個文本中不包含xxx字段的span://span[not(contains(text(),'xxx'))]
xpath的學習-補充
絕對路徑html/body/div/span[2]/input[2] 中間結構變化,就失效
相對路徑//開始扮匠,在整個html source里找捧请,不管在什么位置
索引[x]//div/input[2] div下面第二個input
position()=2position()>3position()<3
例如html:
test position()1
test position()2
test position()3
test position()4
test position()5
獲取第一個span,可以是//div[@id='positions']/span[1]棒搜,也可以是//div[@id='positions']/span[position()=1]
//div[@id='positions']/span[position()>3]就是定位了test position()4和test position()5
//div[@id='positions']/span[position()<3]就是定位了test position()1和test position()2
last()last()-1
以上面的html為例子疹蛉,獲取最后一個span://div[@id='positions']/span[last()]
以上面的html為例子,獲取倒數(shù)第二個span://div[@id='positions']/span[last()-1]
屬性定位@class ? //div[@class] ?有class屬性的div
屬性值定位力麸,前面已經(jīng)講過了 ?//div[@class='xxx']
功能關鍵字
1.常用
and/[][]可款,比如://span[@name='xxx' and text()='xxx']也是可以寫成//span[@name='xxx'][text()='xxx']
or,比如以上面html為例子克蚂,定位文本為test position()5和test position()4的span://div[@id='positions']/span[text()='test position()5' or text()='test position()4']
not,contains,starts-with
ends-with 在xpath中是沒有這個的
2.不常用的
substring,substring-before,substing-after
sbustring(str,start-position,length)比如html:
text
定位上面html中span://div[@id='xxx']/span[substring(@name,3,5)='xxxxx']
substring-before的用法闺鲸,比如html
text
定位上面html中span://div[@id="xxx"]/span[sbustring-before(@class,"-")="spanclass1"]
substring-after的用法,比如html
text
定位上面html中span://div[@id="xxx"]/span[sbustring-after(@class,"-")="spanclass22"]
通配符 ?*
比如//span[@*="xxx"]指定位span中任意屬性包含xxx的
比如//*[@*="xxx"]指定位頁面中任意屬性保護xxx的標簽
Axes 軸
parent 父節(jié)點
ancestor 祖先節(jié)點埃叭,包括父節(jié)點摸恍,一層一層向上
descendant 所有子孫節(jié)點找,不管什么位置赤屋,簡寫//立镶,就是xpath中出現(xiàn)//的情況壁袄。。//div[@class="xxx"]//input
follwing-sibling 當前元素后面的兄弟姐妹
preceding-sibling 當前元素前面的兄弟姐妹
following 當前元素后面所有元素谜慌,一直到
preceding ?當前元素之前所有元素然想,一直到
ancestor-or-self
descendant-or-self
使用的時候注意加上::