xpath定位的总结

一、选取节点

1.节点名(基本不用)

-非常广泛 -不够精准

2.从根节点选取(基本不用)

  • /html/head/title

  • 路径往往非常长

  • 需要从根节点开始一级一级往下写

3.从根节点开始往下查找,直到找到符合要求的节点//

  • 相对路径定位

  • 用的最多

  • //h4/a

定位的原则:

  • 稳定

  • 简单、灵活

  • 唯一

4.选取当前节点

  • /.获取当前节点

5.选取上一级父节点

  • 使用..

6.@选取属性

  • //a[@class]

    • 将拥有class属性的所有a标签获取到

  • //span[@class="js-label"]

  • 标签名[@属性名="属性值"

  • //div[@id="solutiontop"]

7.contains 包含

  • //div[contains(@id,"solution")]

  • //input[contains(@class,"btn")]

8.text()文本定位

  • //span[text()=" 津京冀"]

  • //span[contains(text()," 津京冀")]

9.多条件定位

  • and

    • //input[@name and @class="s_ipt"]

  • or

    • //input[@id="kw" or @id="su"]

10.通过上一级来定位

  • //a[@title="Python"]/span[@class="js-label"]

11.通配符定位节点

  • //*

    • 匹配所有节点

  • //[@]

    • 匹配所有拥有属性的节点

12.轴定位

  • 能够找到唯一的中心点(轴点)

  • parent 父节点

  • ancestor 祖先节点(包含父节点)

  • preceding 当前元素节点之前的所有节点(先辈节点)

  • preceding-sibling 当前节点之前的所有兄弟节点

  • following 后辈节点

    • //span[@class='soutu-btn']/following::input[@id='su']

  • following-sibling 当前节点之后的所有兄弟节点

  • //a[text()='SQL']/parent::li//following-sibling::li/child::a[text()="Python"]

  • //d[@ddt-vale="1992"]/following-sibling::dd[contains(@class,"batscore")]//span

13.按位置索引获取节点

  • 获取同一个节点

  • 从1开始

  • //div[@data-report-module="middle-course"]/ul/li[1]

  • //div[@data-report-module="middle-course"]/ul/li[position()>20]

  • //div[@data-report-module="middle-course"]/ul/li[last()]

  • //div[@data-report-module="middle-course"]/ul/li[last()-1] 倒数第二个

 

 

 

原文地址:https://www.cnblogs.com/fyangq/p/12530217.html