xpath定位

  1. contains (): //div[contains(@id,'in')] ,表示选择id中包含有’in’的div节点
    2.text():由于一个节点的文本值不属于属性,比如“<a class=”baidu“ href=” http://www.baidu.com 

    “>baidu</a>”,所以,用text()函数来匹配节点://a[text()='baidu']
    3.last():前面已介绍
    4.starts-with(): //div[starts-with(@id,'in')] ,表示选择以’in’开头的id属性的div节点
    5.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)]

 

http://www.w3school.com.cn/example/xmle/books.xml

练习:找到最后一个title

方法1://title[.='XQuery Kick Start'] 

方法2://book[@category='web' and not(@cover)]/title

方法3://author[text()="James McGovern"]/../title 

方法4:/bookstore/book/title[.="XQuery Kick Start"]1

 

文本中包含某一部分 //book/*[contains(text(),'De')]

属性中包含某一部分//book[contains(@category,'oo')] 

 

二、亲属匹配关系:

parent::* 表示当前节点的父节点元素

ancestor::* 表示当前节点的祖先节点元素

child::* 表示当前节点的子元素 /A/descendant::* 表示A的所有后代元素

self::* 表示当前节点的自身元素

ancestor-or-self::* 表示当前节点的及它的祖先节点元素

descendant-or-self::* 表示当前节点的及它们的后代元素

following-sibling::* 表示当前节点的后序所有兄弟节点元素

preceding-sibling::* 表示当前节点的前面所有兄弟节点元素

following::* 表示当前节点的后序所有元素

preceding::* 表示当前节点的所有元素

 

举例:

//price[.=39.95]/preceding-sibling::* 

//price[.=39.95]/preceding-sibling::year 

 

练习:基于第三本书元素的位置,查找4个元素:
1 第二本书的元素
2 第四本书的元素
3 父节点书的元素
4 子节点中year元素

自己写的:

//book[3]/preceding-sibling::*[1]

//book[3]/following-sibling::*[1]

//book[3]/parent::*

//book[3]/descendant-or-self::year

 

老师:

1 ://book[3]/preceding-sibling::book[1]

 

2 //book[3]/following-sibling::book[1] 

3 //book[3]/..                

//book[3]/parent::bookstore 

4 //book[3]/child::year
/bookstore/child::book[1]/child::year 

 

基于轴去找,非常强大

孙节点:/bookstore/descendant::year[1] 

找祖先://price[.='29.99']/ancestor::bookstore 

 

//book[@*[2]]

 查找有第二个属性的book

 

 

总结:

 

定位的思路:

1 能用id就用id

2 尽量别用绝对定位,多用相对定位方式

3 难定位的时候,常用三种方式

  * 查看元素是否有唯一的与众不同的属性值

  * 使用 and 将元素的多个属性进行组合,查看组合的多个属性

  * 使用轴,先一个目标元素周围的元素,找到一个好定位的,然后

使用相对位置的方式,使用轴来进行定位。

4 使用contains函数进行文字的部分文字匹配

//p[contains(.,"gloryroad")]

 

 

 

 

 

练习:页面不断变化的id,如何定位

http://mail.126.com/  定位输入框

 

//input[@placeholder="邮箱帐号或手机号"]   尝试去找唯一性的文字

 

或者 //input[contains(@id,'auto-id') and @name="email"]  尝试使用contains模糊匹配,匹配不到的加and条件,再匹配一个

 

 

 

 

 

 

 

 

posted @ 2018-03-21 22:54  小七Libra  阅读(167)  评论(0编辑  收藏  举报