一、寫在前面
之前寫過一些關於元素定位的文章,但是感覺都是很碎片,現在想做個整合,便有了這篇文章。
二、xpath的定位方法
關於Xpath
定位方法,網上寫的已經很成熟了,現已百度首頁為例,如下圖:
再結合我之前所寫整理如下。
1、通過絕對路徑方式定位
/html/body/div[1]/div[2]/div[5]/div[1]/div/form/span[1]/input
2、通過相對路徑方式定位
//input
3、通過元素索引定位
//input[4]
4、通過屬性定位
使用xpath屬性定位(結合第2、第3中方法可以使用)
//input[@id='kw']
//input[@type='name' and @name='kw']
5、通過部分屬性值匹配
//input[starts-with(@id,'k')]
//input[ends-with(@id,'w')]
//input[contains(@id,'w')]
6、通過文本定位
//a[text()='直播']
三、關於xpath函數使用舉例說明
1、contains():
//div[contains(@id,'in')] ,表示選擇id中包含有’in’的div節點
2、text()
//a[text()='baidu'] ,用text()函數來匹配節點
3、last()
book[last()] ,取xpath最后一個book元素
book[last()-1] ,取xpath最后第二個book元素
4、starts-with()
//div[starts-with(@id,'in')] ,表示選擇以’in’開頭的id屬性的div節點
5、not()
not()
函數,表示否定
//input[@name=‘identity’ and not(contains(@class,‘a’))] ,表示匹配出name為identity並且class的值中不包含a的input節點。
特別注意
not()
函數通常與返回值為true or false
的函數組合起來用contains(),starts-with()
等,但有一種特別情況請注意一下。
我們要匹配出input節點含有id屬性的,寫法如下://input[@id]
,如果我們要匹配出input節點不含用id屬性的,則為://input[not(@id)]
。
xpath
中的ends-with
無效,原因如下:
ends-with
是xpath2.0
的語法,可能你的瀏覽器還只支持1.0的語法。